1 //===--- CGStmt.cpp - Emit LLVM Code from Statements ----------------------===//
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 contains code to emit Stmt nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGDebugInfo.h"
16 #include "CodeGenModule.h"
17 #include "TargetInfo.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/Basic/PrettyStackTrace.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Sema/LoopHint.h"
22 #include "clang/Sema/SemaDiagnostic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/IR/CallSite.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/InlineAsm.h"
27 #include "llvm/IR/Intrinsics.h"
28 using namespace clang;
29 using namespace CodeGen;
30 
31 //===----------------------------------------------------------------------===//
32 //                              Statement Emission
33 //===----------------------------------------------------------------------===//
34 
35 void CodeGenFunction::EmitStopPoint(const Stmt *S) {
36   if (CGDebugInfo *DI = getDebugInfo()) {
37     SourceLocation Loc;
38     Loc = S->getLocStart();
39     DI->EmitLocation(Builder, Loc);
40 
41     LastStopPoint = Loc;
42   }
43 }
44 
45 void CodeGenFunction::EmitStmt(const Stmt *S) {
46   assert(S && "Null statement?");
47   PGO.setCurrentStmt(S);
48 
49   // These statements have their own debug info handling.
50   if (EmitSimpleStmt(S))
51     return;
52 
53   // Check if we are generating unreachable code.
54   if (!HaveInsertPoint()) {
55     // If so, and the statement doesn't contain a label, then we do not need to
56     // generate actual code. This is safe because (1) the current point is
57     // unreachable, so we don't need to execute the code, and (2) we've already
58     // handled the statements which update internal data structures (like the
59     // local variable map) which could be used by subsequent statements.
60     if (!ContainsLabel(S)) {
61       // Verify that any decl statements were handled as simple, they may be in
62       // scope of subsequent reachable statements.
63       assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!");
64       return;
65     }
66 
67     // Otherwise, make a new block to hold the code.
68     EnsureInsertPoint();
69   }
70 
71   // Generate a stoppoint if we are emitting debug info.
72   EmitStopPoint(S);
73 
74   switch (S->getStmtClass()) {
75   case Stmt::NoStmtClass:
76   case Stmt::CXXCatchStmtClass:
77   case Stmt::SEHExceptStmtClass:
78   case Stmt::SEHFinallyStmtClass:
79   case Stmt::MSDependentExistsStmtClass:
80     llvm_unreachable("invalid statement class to emit generically");
81   case Stmt::NullStmtClass:
82   case Stmt::CompoundStmtClass:
83   case Stmt::DeclStmtClass:
84   case Stmt::LabelStmtClass:
85   case Stmt::AttributedStmtClass:
86   case Stmt::GotoStmtClass:
87   case Stmt::BreakStmtClass:
88   case Stmt::ContinueStmtClass:
89   case Stmt::DefaultStmtClass:
90   case Stmt::CaseStmtClass:
91     llvm_unreachable("should have emitted these statements as simple");
92 
93 #define STMT(Type, Base)
94 #define ABSTRACT_STMT(Op)
95 #define EXPR(Type, Base) \
96   case Stmt::Type##Class:
97 #include "clang/AST/StmtNodes.inc"
98   {
99     // Remember the block we came in on.
100     llvm::BasicBlock *incoming = Builder.GetInsertBlock();
101     assert(incoming && "expression emission must have an insertion point");
102 
103     EmitIgnoredExpr(cast<Expr>(S));
104 
105     llvm::BasicBlock *outgoing = Builder.GetInsertBlock();
106     assert(outgoing && "expression emission cleared block!");
107 
108     // The expression emitters assume (reasonably!) that the insertion
109     // point is always set.  To maintain that, the call-emission code
110     // for noreturn functions has to enter a new block with no
111     // predecessors.  We want to kill that block and mark the current
112     // insertion point unreachable in the common case of a call like
113     // "exit();".  Since expression emission doesn't otherwise create
114     // blocks with no predecessors, we can just test for that.
115     // However, we must be careful not to do this to our incoming
116     // block, because *statement* emission does sometimes create
117     // reachable blocks which will have no predecessors until later in
118     // the function.  This occurs with, e.g., labels that are not
119     // reachable by fallthrough.
120     if (incoming != outgoing && outgoing->use_empty()) {
121       outgoing->eraseFromParent();
122       Builder.ClearInsertionPoint();
123     }
124     break;
125   }
126 
127   case Stmt::IndirectGotoStmtClass:
128     EmitIndirectGotoStmt(cast<IndirectGotoStmt>(*S)); break;
129 
130   case Stmt::IfStmtClass:       EmitIfStmt(cast<IfStmt>(*S));             break;
131   case Stmt::WhileStmtClass:    EmitWhileStmt(cast<WhileStmt>(*S));       break;
132   case Stmt::DoStmtClass:       EmitDoStmt(cast<DoStmt>(*S));             break;
133   case Stmt::ForStmtClass:      EmitForStmt(cast<ForStmt>(*S));           break;
134 
135   case Stmt::ReturnStmtClass:   EmitReturnStmt(cast<ReturnStmt>(*S));     break;
136 
137   case Stmt::SwitchStmtClass:   EmitSwitchStmt(cast<SwitchStmt>(*S));     break;
138   case Stmt::GCCAsmStmtClass:   // Intentional fall-through.
139   case Stmt::MSAsmStmtClass:    EmitAsmStmt(cast<AsmStmt>(*S));           break;
140   case Stmt::CapturedStmtClass: {
141     const CapturedStmt *CS = cast<CapturedStmt>(S);
142     EmitCapturedStmt(*CS, CS->getCapturedRegionKind());
143     }
144     break;
145   case Stmt::ObjCAtTryStmtClass:
146     EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
147     break;
148   case Stmt::ObjCAtCatchStmtClass:
149     llvm_unreachable(
150                     "@catch statements should be handled by EmitObjCAtTryStmt");
151   case Stmt::ObjCAtFinallyStmtClass:
152     llvm_unreachable(
153                   "@finally statements should be handled by EmitObjCAtTryStmt");
154   case Stmt::ObjCAtThrowStmtClass:
155     EmitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(*S));
156     break;
157   case Stmt::ObjCAtSynchronizedStmtClass:
158     EmitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(*S));
159     break;
160   case Stmt::ObjCForCollectionStmtClass:
161     EmitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(*S));
162     break;
163   case Stmt::ObjCAutoreleasePoolStmtClass:
164     EmitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(*S));
165     break;
166 
167   case Stmt::CXXTryStmtClass:
168     EmitCXXTryStmt(cast<CXXTryStmt>(*S));
169     break;
170   case Stmt::CXXForRangeStmtClass:
171     EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*S));
172     break;
173   case Stmt::SEHTryStmtClass:
174     EmitSEHTryStmt(cast<SEHTryStmt>(*S));
175     break;
176   case Stmt::SEHLeaveStmtClass:
177     EmitSEHLeaveStmt(cast<SEHLeaveStmt>(*S));
178     break;
179   case Stmt::OMPParallelDirectiveClass:
180     EmitOMPParallelDirective(cast<OMPParallelDirective>(*S));
181     break;
182   case Stmt::OMPSimdDirectiveClass:
183     EmitOMPSimdDirective(cast<OMPSimdDirective>(*S));
184     break;
185   case Stmt::OMPForDirectiveClass:
186     EmitOMPForDirective(cast<OMPForDirective>(*S));
187     break;
188   case Stmt::OMPSectionsDirectiveClass:
189     EmitOMPSectionsDirective(cast<OMPSectionsDirective>(*S));
190     break;
191   case Stmt::OMPSectionDirectiveClass:
192     EmitOMPSectionDirective(cast<OMPSectionDirective>(*S));
193     break;
194   case Stmt::OMPSingleDirectiveClass:
195     EmitOMPSingleDirective(cast<OMPSingleDirective>(*S));
196     break;
197   case Stmt::OMPParallelForDirectiveClass:
198     EmitOMPParallelForDirective(cast<OMPParallelForDirective>(*S));
199     break;
200   case Stmt::OMPParallelSectionsDirectiveClass:
201     EmitOMPParallelSectionsDirective(cast<OMPParallelSectionsDirective>(*S));
202     break;
203   case Stmt::OMPTaskDirectiveClass:
204     EmitOMPTaskDirective(cast<OMPTaskDirective>(*S));
205     break;
206   }
207 }
208 
209 bool CodeGenFunction::EmitSimpleStmt(const Stmt *S) {
210   switch (S->getStmtClass()) {
211   default: return false;
212   case Stmt::NullStmtClass: break;
213   case Stmt::CompoundStmtClass: EmitCompoundStmt(cast<CompoundStmt>(*S)); break;
214   case Stmt::DeclStmtClass:     EmitDeclStmt(cast<DeclStmt>(*S));         break;
215   case Stmt::LabelStmtClass:    EmitLabelStmt(cast<LabelStmt>(*S));       break;
216   case Stmt::AttributedStmtClass:
217                             EmitAttributedStmt(cast<AttributedStmt>(*S)); break;
218   case Stmt::GotoStmtClass:     EmitGotoStmt(cast<GotoStmt>(*S));         break;
219   case Stmt::BreakStmtClass:    EmitBreakStmt(cast<BreakStmt>(*S));       break;
220   case Stmt::ContinueStmtClass: EmitContinueStmt(cast<ContinueStmt>(*S)); break;
221   case Stmt::DefaultStmtClass:  EmitDefaultStmt(cast<DefaultStmt>(*S));   break;
222   case Stmt::CaseStmtClass:     EmitCaseStmt(cast<CaseStmt>(*S));         break;
223   }
224 
225   return true;
226 }
227 
228 /// EmitCompoundStmt - Emit a compound statement {..} node.  If GetLast is true,
229 /// this captures the expression result of the last sub-statement and returns it
230 /// (for use by the statement expression extension).
231 llvm::Value* CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast,
232                                                AggValueSlot AggSlot) {
233   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(),
234                              "LLVM IR generation of compound statement ('{}')");
235 
236   // Keep track of the current cleanup stack depth, including debug scopes.
237   LexicalScope Scope(*this, S.getSourceRange());
238 
239   return EmitCompoundStmtWithoutScope(S, GetLast, AggSlot);
240 }
241 
242 llvm::Value*
243 CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S,
244                                               bool GetLast,
245                                               AggValueSlot AggSlot) {
246 
247   for (CompoundStmt::const_body_iterator I = S.body_begin(),
248        E = S.body_end()-GetLast; I != E; ++I)
249     EmitStmt(*I);
250 
251   llvm::Value *RetAlloca = nullptr;
252   if (GetLast) {
253     // We have to special case labels here.  They are statements, but when put
254     // at the end of a statement expression, they yield the value of their
255     // subexpression.  Handle this by walking through all labels we encounter,
256     // emitting them before we evaluate the subexpr.
257     const Stmt *LastStmt = S.body_back();
258     while (const LabelStmt *LS = dyn_cast<LabelStmt>(LastStmt)) {
259       EmitLabel(LS->getDecl());
260       LastStmt = LS->getSubStmt();
261     }
262 
263     EnsureInsertPoint();
264 
265     QualType ExprTy = cast<Expr>(LastStmt)->getType();
266     if (hasAggregateEvaluationKind(ExprTy)) {
267       EmitAggExpr(cast<Expr>(LastStmt), AggSlot);
268     } else {
269       // We can't return an RValue here because there might be cleanups at
270       // the end of the StmtExpr.  Because of that, we have to emit the result
271       // here into a temporary alloca.
272       RetAlloca = CreateMemTemp(ExprTy);
273       EmitAnyExprToMem(cast<Expr>(LastStmt), RetAlloca, Qualifiers(),
274                        /*IsInit*/false);
275     }
276 
277   }
278 
279   return RetAlloca;
280 }
281 
282 void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) {
283   llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(BB->getTerminator());
284 
285   // If there is a cleanup stack, then we it isn't worth trying to
286   // simplify this block (we would need to remove it from the scope map
287   // and cleanup entry).
288   if (!EHStack.empty())
289     return;
290 
291   // Can only simplify direct branches.
292   if (!BI || !BI->isUnconditional())
293     return;
294 
295   // Can only simplify empty blocks.
296   if (BI != BB->begin())
297     return;
298 
299   BB->replaceAllUsesWith(BI->getSuccessor(0));
300   BI->eraseFromParent();
301   BB->eraseFromParent();
302 }
303 
304 void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) {
305   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
306 
307   // Fall out of the current block (if necessary).
308   EmitBranch(BB);
309 
310   if (IsFinished && BB->use_empty()) {
311     delete BB;
312     return;
313   }
314 
315   // Place the block after the current block, if possible, or else at
316   // the end of the function.
317   if (CurBB && CurBB->getParent())
318     CurFn->getBasicBlockList().insertAfter(CurBB, BB);
319   else
320     CurFn->getBasicBlockList().push_back(BB);
321   Builder.SetInsertPoint(BB);
322 }
323 
324 void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) {
325   // Emit a branch from the current block to the target one if this
326   // was a real block.  If this was just a fall-through block after a
327   // terminator, don't emit it.
328   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
329 
330   if (!CurBB || CurBB->getTerminator()) {
331     // If there is no insert point or the previous block is already
332     // terminated, don't touch it.
333   } else {
334     // Otherwise, create a fall-through branch.
335     Builder.CreateBr(Target);
336   }
337 
338   Builder.ClearInsertionPoint();
339 }
340 
341 void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) {
342   bool inserted = false;
343   for (llvm::User *u : block->users()) {
344     if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(u)) {
345       CurFn->getBasicBlockList().insertAfter(insn->getParent(), block);
346       inserted = true;
347       break;
348     }
349   }
350 
351   if (!inserted)
352     CurFn->getBasicBlockList().push_back(block);
353 
354   Builder.SetInsertPoint(block);
355 }
356 
357 CodeGenFunction::JumpDest
358 CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
359   JumpDest &Dest = LabelMap[D];
360   if (Dest.isValid()) return Dest;
361 
362   // Create, but don't insert, the new block.
363   Dest = JumpDest(createBasicBlock(D->getName()),
364                   EHScopeStack::stable_iterator::invalid(),
365                   NextCleanupDestIndex++);
366   return Dest;
367 }
368 
369 void CodeGenFunction::EmitLabel(const LabelDecl *D) {
370   // Add this label to the current lexical scope if we're within any
371   // normal cleanups.  Jumps "in" to this label --- when permitted by
372   // the language --- may need to be routed around such cleanups.
373   if (EHStack.hasNormalCleanups() && CurLexicalScope)
374     CurLexicalScope->addLabel(D);
375 
376   JumpDest &Dest = LabelMap[D];
377 
378   // If we didn't need a forward reference to this label, just go
379   // ahead and create a destination at the current scope.
380   if (!Dest.isValid()) {
381     Dest = getJumpDestInCurrentScope(D->getName());
382 
383   // Otherwise, we need to give this label a target depth and remove
384   // it from the branch-fixups list.
385   } else {
386     assert(!Dest.getScopeDepth().isValid() && "already emitted label!");
387     Dest.setScopeDepth(EHStack.stable_begin());
388     ResolveBranchFixups(Dest.getBlock());
389   }
390 
391   RegionCounter Cnt = getPGORegionCounter(D->getStmt());
392   EmitBlock(Dest.getBlock());
393   Cnt.beginRegion(Builder);
394 }
395 
396 /// Change the cleanup scope of the labels in this lexical scope to
397 /// match the scope of the enclosing context.
398 void CodeGenFunction::LexicalScope::rescopeLabels() {
399   assert(!Labels.empty());
400   EHScopeStack::stable_iterator innermostScope
401     = CGF.EHStack.getInnermostNormalCleanup();
402 
403   // Change the scope depth of all the labels.
404   for (SmallVectorImpl<const LabelDecl*>::const_iterator
405          i = Labels.begin(), e = Labels.end(); i != e; ++i) {
406     assert(CGF.LabelMap.count(*i));
407     JumpDest &dest = CGF.LabelMap.find(*i)->second;
408     assert(dest.getScopeDepth().isValid());
409     assert(innermostScope.encloses(dest.getScopeDepth()));
410     dest.setScopeDepth(innermostScope);
411   }
412 
413   // Reparent the labels if the new scope also has cleanups.
414   if (innermostScope != EHScopeStack::stable_end() && ParentScope) {
415     ParentScope->Labels.append(Labels.begin(), Labels.end());
416   }
417 }
418 
419 
420 void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) {
421   EmitLabel(S.getDecl());
422   EmitStmt(S.getSubStmt());
423 }
424 
425 void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) {
426   const Stmt *SubStmt = S.getSubStmt();
427   switch (SubStmt->getStmtClass()) {
428   case Stmt::DoStmtClass:
429     EmitDoStmt(cast<DoStmt>(*SubStmt), S.getAttrs());
430     break;
431   case Stmt::ForStmtClass:
432     EmitForStmt(cast<ForStmt>(*SubStmt), S.getAttrs());
433     break;
434   case Stmt::WhileStmtClass:
435     EmitWhileStmt(cast<WhileStmt>(*SubStmt), S.getAttrs());
436     break;
437   case Stmt::CXXForRangeStmtClass:
438     EmitCXXForRangeStmt(cast<CXXForRangeStmt>(*SubStmt), S.getAttrs());
439     break;
440   default:
441     EmitStmt(SubStmt);
442   }
443 }
444 
445 void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
446   // If this code is reachable then emit a stop point (if generating
447   // debug info). We have to do this ourselves because we are on the
448   // "simple" statement path.
449   if (HaveInsertPoint())
450     EmitStopPoint(&S);
451 
452   EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
453 }
454 
455 
456 void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
457   if (const LabelDecl *Target = S.getConstantTarget()) {
458     EmitBranchThroughCleanup(getJumpDestForLabel(Target));
459     return;
460   }
461 
462   // Ensure that we have an i8* for our PHI node.
463   llvm::Value *V = Builder.CreateBitCast(EmitScalarExpr(S.getTarget()),
464                                          Int8PtrTy, "addr");
465   llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
466 
467   // Get the basic block for the indirect goto.
468   llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock();
469 
470   // The first instruction in the block has to be the PHI for the switch dest,
471   // add an entry for this branch.
472   cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
473 
474   EmitBranch(IndGotoBB);
475 }
476 
477 void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
478   // C99 6.8.4.1: The first substatement is executed if the expression compares
479   // unequal to 0.  The condition must be a scalar type.
480   LexicalScope ConditionScope(*this, S.getCond()->getSourceRange());
481   RegionCounter Cnt = getPGORegionCounter(&S);
482 
483   if (S.getConditionVariable())
484     EmitAutoVarDecl(*S.getConditionVariable());
485 
486   // If the condition constant folds and can be elided, try to avoid emitting
487   // the condition and the dead arm of the if/else.
488   bool CondConstant;
489   if (ConstantFoldsToSimpleInteger(S.getCond(), CondConstant)) {
490     // Figure out which block (then or else) is executed.
491     const Stmt *Executed = S.getThen();
492     const Stmt *Skipped  = S.getElse();
493     if (!CondConstant)  // Condition false?
494       std::swap(Executed, Skipped);
495 
496     // If the skipped block has no labels in it, just emit the executed block.
497     // This avoids emitting dead code and simplifies the CFG substantially.
498     if (!ContainsLabel(Skipped)) {
499       if (CondConstant)
500         Cnt.beginRegion(Builder);
501       if (Executed) {
502         RunCleanupsScope ExecutedScope(*this);
503         EmitStmt(Executed);
504       }
505       return;
506     }
507   }
508 
509   // Otherwise, the condition did not fold, or we couldn't elide it.  Just emit
510   // the conditional branch.
511   llvm::BasicBlock *ThenBlock = createBasicBlock("if.then");
512   llvm::BasicBlock *ContBlock = createBasicBlock("if.end");
513   llvm::BasicBlock *ElseBlock = ContBlock;
514   if (S.getElse())
515     ElseBlock = createBasicBlock("if.else");
516 
517   EmitBranchOnBoolExpr(S.getCond(), ThenBlock, ElseBlock, Cnt.getCount());
518 
519   // Emit the 'then' code.
520   EmitBlock(ThenBlock);
521   Cnt.beginRegion(Builder);
522   {
523     RunCleanupsScope ThenScope(*this);
524     EmitStmt(S.getThen());
525   }
526   EmitBranch(ContBlock);
527 
528   // Emit the 'else' code if present.
529   if (const Stmt *Else = S.getElse()) {
530     {
531       // There is no need to emit line number for unconditional branch.
532       SuppressDebugLocation S(Builder);
533       EmitBlock(ElseBlock);
534     }
535     {
536       RunCleanupsScope ElseScope(*this);
537       EmitStmt(Else);
538     }
539     {
540       // There is no need to emit line number for unconditional branch.
541       SuppressDebugLocation S(Builder);
542       EmitBranch(ContBlock);
543     }
544   }
545 
546   // Emit the continuation block for code after the if.
547   EmitBlock(ContBlock, true);
548 }
549 
550 void CodeGenFunction::EmitCondBrHints(llvm::LLVMContext &Context,
551                                       llvm::BranchInst *CondBr,
552                                       const ArrayRef<const Attr *> &Attrs) {
553   // Return if there are no hints.
554   if (Attrs.empty())
555     return;
556 
557   // Add vectorize and unroll hints to the metadata on the conditional branch.
558   SmallVector<llvm::Value *, 2> Metadata(1);
559   for (const auto *Attr : Attrs) {
560     const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(Attr);
561 
562     // Skip non loop hint attributes
563     if (!LH)
564       continue;
565 
566     LoopHintAttr::OptionType Option = LH->getOption();
567     int ValueInt = LH->getValue();
568 
569     const char *MetadataName;
570     switch (Option) {
571     case LoopHintAttr::Vectorize:
572     case LoopHintAttr::VectorizeWidth:
573       MetadataName = "llvm.loop.vectorize.width";
574       break;
575     case LoopHintAttr::Interleave:
576     case LoopHintAttr::InterleaveCount:
577       MetadataName = "llvm.loop.vectorize.unroll";
578       break;
579     case LoopHintAttr::Unroll:
580       MetadataName = "llvm.loop.unroll.enable";
581       break;
582     case LoopHintAttr::UnrollCount:
583       MetadataName = "llvm.loop.unroll.count";
584       break;
585     }
586 
587     llvm::Value *Value;
588     llvm::MDString *Name;
589     switch (Option) {
590     case LoopHintAttr::Vectorize:
591     case LoopHintAttr::Interleave:
592       if (ValueInt == 1) {
593         // FIXME: In the future I will modifiy the behavior of the metadata
594         // so we can enable/disable vectorization and interleaving separately.
595         Name = llvm::MDString::get(Context, "llvm.loop.vectorize.enable");
596         Value = Builder.getTrue();
597         break;
598       }
599       // Vectorization/interleaving is disabled, set width/count to 1.
600       ValueInt = 1;
601       // Fallthrough.
602     case LoopHintAttr::VectorizeWidth:
603     case LoopHintAttr::InterleaveCount:
604       Name = llvm::MDString::get(Context, MetadataName);
605       Value = llvm::ConstantInt::get(Int32Ty, ValueInt);
606       break;
607     case LoopHintAttr::Unroll:
608       Name = llvm::MDString::get(Context, MetadataName);
609       Value = (ValueInt == 0) ? Builder.getFalse() : Builder.getTrue();
610       break;
611     case LoopHintAttr::UnrollCount:
612       Name = llvm::MDString::get(Context, MetadataName);
613       Value = llvm::ConstantInt::get(Int32Ty, ValueInt);
614       break;
615     }
616 
617     SmallVector<llvm::Value *, 2> OpValues;
618     OpValues.push_back(Name);
619     OpValues.push_back(Value);
620 
621     // Set or overwrite metadata indicated by Name.
622     Metadata.push_back(llvm::MDNode::get(Context, OpValues));
623   }
624 
625   if (!Metadata.empty()) {
626     // Add llvm.loop MDNode to CondBr.
627     llvm::MDNode *LoopID = llvm::MDNode::get(Context, Metadata);
628     LoopID->replaceOperandWith(0, LoopID); // First op points to itself.
629 
630     CondBr->setMetadata("llvm.loop", LoopID);
631   }
632 }
633 
634 void CodeGenFunction::EmitWhileStmt(const WhileStmt &S,
635                                     const ArrayRef<const Attr *> &WhileAttrs) {
636   RegionCounter Cnt = getPGORegionCounter(&S);
637 
638   // Emit the header for the loop, which will also become
639   // the continue target.
640   JumpDest LoopHeader = getJumpDestInCurrentScope("while.cond");
641   EmitBlock(LoopHeader.getBlock());
642 
643   LoopStack.push(LoopHeader.getBlock());
644 
645   // Create an exit block for when the condition fails, which will
646   // also become the break target.
647   JumpDest LoopExit = getJumpDestInCurrentScope("while.end");
648 
649   // Store the blocks to use for break and continue.
650   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopHeader));
651 
652   // C++ [stmt.while]p2:
653   //   When the condition of a while statement is a declaration, the
654   //   scope of the variable that is declared extends from its point
655   //   of declaration (3.3.2) to the end of the while statement.
656   //   [...]
657   //   The object created in a condition is destroyed and created
658   //   with each iteration of the loop.
659   RunCleanupsScope ConditionScope(*this);
660 
661   if (S.getConditionVariable())
662     EmitAutoVarDecl(*S.getConditionVariable());
663 
664   // Evaluate the conditional in the while header.  C99 6.8.5.1: The
665   // evaluation of the controlling expression takes place before each
666   // execution of the loop body.
667   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
668 
669   // while(1) is common, avoid extra exit blocks.  Be sure
670   // to correctly handle break/continue though.
671   bool EmitBoolCondBranch = true;
672   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
673     if (C->isOne())
674       EmitBoolCondBranch = false;
675 
676   // As long as the condition is true, go to the loop body.
677   llvm::BasicBlock *LoopBody = createBasicBlock("while.body");
678   if (EmitBoolCondBranch) {
679     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
680     if (ConditionScope.requiresCleanups())
681       ExitBlock = createBasicBlock("while.exit");
682     llvm::BranchInst *CondBr =
683         Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock,
684                              PGO.createLoopWeights(S.getCond(), Cnt));
685 
686     if (ExitBlock != LoopExit.getBlock()) {
687       EmitBlock(ExitBlock);
688       EmitBranchThroughCleanup(LoopExit);
689     }
690 
691     // Attach metadata to loop body conditional branch.
692     EmitCondBrHints(LoopBody->getContext(), CondBr, WhileAttrs);
693   }
694 
695   // Emit the loop body.  We have to emit this in a cleanup scope
696   // because it might be a singleton DeclStmt.
697   {
698     RunCleanupsScope BodyScope(*this);
699     EmitBlock(LoopBody);
700     Cnt.beginRegion(Builder);
701     EmitStmt(S.getBody());
702   }
703 
704   BreakContinueStack.pop_back();
705 
706   // Immediately force cleanup.
707   ConditionScope.ForceCleanup();
708 
709   // Branch to the loop header again.
710   EmitBranch(LoopHeader.getBlock());
711 
712   LoopStack.pop();
713 
714   // Emit the exit block.
715   EmitBlock(LoopExit.getBlock(), true);
716 
717   // The LoopHeader typically is just a branch if we skipped emitting
718   // a branch, try to erase it.
719   if (!EmitBoolCondBranch)
720     SimplifyForwardingBlocks(LoopHeader.getBlock());
721 }
722 
723 void CodeGenFunction::EmitDoStmt(const DoStmt &S,
724                                  const ArrayRef<const Attr *> &DoAttrs) {
725   JumpDest LoopExit = getJumpDestInCurrentScope("do.end");
726   JumpDest LoopCond = getJumpDestInCurrentScope("do.cond");
727 
728   RegionCounter Cnt = getPGORegionCounter(&S);
729 
730   // Store the blocks to use for break and continue.
731   BreakContinueStack.push_back(BreakContinue(LoopExit, LoopCond));
732 
733   // Emit the body of the loop.
734   llvm::BasicBlock *LoopBody = createBasicBlock("do.body");
735 
736   LoopStack.push(LoopBody);
737 
738   EmitBlockWithFallThrough(LoopBody, Cnt);
739   {
740     RunCleanupsScope BodyScope(*this);
741     EmitStmt(S.getBody());
742   }
743 
744   EmitBlock(LoopCond.getBlock());
745 
746   // C99 6.8.5.2: "The evaluation of the controlling expression takes place
747   // after each execution of the loop body."
748 
749   // Evaluate the conditional in the while header.
750   // C99 6.8.5p2/p4: The first substatement is executed if the expression
751   // compares unequal to 0.  The condition must be a scalar type.
752   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
753 
754   BreakContinueStack.pop_back();
755 
756   // "do {} while (0)" is common in macros, avoid extra blocks.  Be sure
757   // to correctly handle break/continue though.
758   bool EmitBoolCondBranch = true;
759   if (llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(BoolCondVal))
760     if (C->isZero())
761       EmitBoolCondBranch = false;
762 
763   // As long as the condition is true, iterate the loop.
764   if (EmitBoolCondBranch) {
765     llvm::BranchInst *CondBr =
766         Builder.CreateCondBr(BoolCondVal, LoopBody, LoopExit.getBlock(),
767                              PGO.createLoopWeights(S.getCond(), Cnt));
768 
769     // Attach metadata to loop body conditional branch.
770     EmitCondBrHints(LoopBody->getContext(), CondBr, DoAttrs);
771   }
772 
773   LoopStack.pop();
774 
775   // Emit the exit block.
776   EmitBlock(LoopExit.getBlock());
777 
778   // The DoCond block typically is just a branch if we skipped
779   // emitting a branch, try to erase it.
780   if (!EmitBoolCondBranch)
781     SimplifyForwardingBlocks(LoopCond.getBlock());
782 }
783 
784 void CodeGenFunction::EmitForStmt(const ForStmt &S,
785                                   const ArrayRef<const Attr *> &ForAttrs) {
786   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
787 
788   RunCleanupsScope ForScope(*this);
789 
790   CGDebugInfo *DI = getDebugInfo();
791   if (DI)
792     DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
793 
794   // Evaluate the first part before the loop.
795   if (S.getInit())
796     EmitStmt(S.getInit());
797 
798   RegionCounter Cnt = getPGORegionCounter(&S);
799 
800   // Start the loop with a block that tests the condition.
801   // If there's an increment, the continue scope will be overwritten
802   // later.
803   JumpDest Continue = getJumpDestInCurrentScope("for.cond");
804   llvm::BasicBlock *CondBlock = Continue.getBlock();
805   EmitBlock(CondBlock);
806 
807   LoopStack.push(CondBlock);
808 
809   // If the for loop doesn't have an increment we can just use the
810   // condition as the continue block.  Otherwise we'll need to create
811   // a block for it (in the current scope, i.e. in the scope of the
812   // condition), and that we will become our continue block.
813   if (S.getInc())
814     Continue = getJumpDestInCurrentScope("for.inc");
815 
816   // Store the blocks to use for break and continue.
817   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
818 
819   // Create a cleanup scope for the condition variable cleanups.
820   RunCleanupsScope ConditionScope(*this);
821 
822   if (S.getCond()) {
823     // If the for statement has a condition scope, emit the local variable
824     // declaration.
825     if (S.getConditionVariable()) {
826       EmitAutoVarDecl(*S.getConditionVariable());
827     }
828 
829     llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
830     // If there are any cleanups between here and the loop-exit scope,
831     // create a block to stage a loop exit along.
832     if (ForScope.requiresCleanups())
833       ExitBlock = createBasicBlock("for.cond.cleanup");
834 
835     // As long as the condition is true, iterate the loop.
836     llvm::BasicBlock *ForBody = createBasicBlock("for.body");
837 
838     // C99 6.8.5p2/p4: The first substatement is executed if the expression
839     // compares unequal to 0.  The condition must be a scalar type.
840     llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
841     llvm::BranchInst *CondBr =
842         Builder.CreateCondBr(BoolCondVal, ForBody, ExitBlock,
843                              PGO.createLoopWeights(S.getCond(), Cnt));
844 
845     // Attach metadata to loop body conditional branch.
846     EmitCondBrHints(ForBody->getContext(), CondBr, ForAttrs);
847 
848     if (ExitBlock != LoopExit.getBlock()) {
849       EmitBlock(ExitBlock);
850       EmitBranchThroughCleanup(LoopExit);
851     }
852 
853     EmitBlock(ForBody);
854   } else {
855     // Treat it as a non-zero constant.  Don't even create a new block for the
856     // body, just fall into it.
857   }
858   Cnt.beginRegion(Builder);
859 
860   {
861     // Create a separate cleanup scope for the body, in case it is not
862     // a compound statement.
863     RunCleanupsScope BodyScope(*this);
864     EmitStmt(S.getBody());
865   }
866 
867   // If there is an increment, emit it next.
868   if (S.getInc()) {
869     EmitBlock(Continue.getBlock());
870     EmitStmt(S.getInc());
871   }
872 
873   BreakContinueStack.pop_back();
874 
875   ConditionScope.ForceCleanup();
876   EmitBranch(CondBlock);
877 
878   ForScope.ForceCleanup();
879 
880   if (DI)
881     DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
882 
883   LoopStack.pop();
884 
885   // Emit the fall-through block.
886   EmitBlock(LoopExit.getBlock(), true);
887 }
888 
889 void
890 CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S,
891                                      const ArrayRef<const Attr *> &ForAttrs) {
892   JumpDest LoopExit = getJumpDestInCurrentScope("for.end");
893 
894   RunCleanupsScope ForScope(*this);
895 
896   CGDebugInfo *DI = getDebugInfo();
897   if (DI)
898     DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
899 
900   // Evaluate the first pieces before the loop.
901   EmitStmt(S.getRangeStmt());
902   EmitStmt(S.getBeginEndStmt());
903 
904   RegionCounter Cnt = getPGORegionCounter(&S);
905 
906   // Start the loop with a block that tests the condition.
907   // If there's an increment, the continue scope will be overwritten
908   // later.
909   llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
910   EmitBlock(CondBlock);
911 
912   LoopStack.push(CondBlock);
913 
914   // If there are any cleanups between here and the loop-exit scope,
915   // create a block to stage a loop exit along.
916   llvm::BasicBlock *ExitBlock = LoopExit.getBlock();
917   if (ForScope.requiresCleanups())
918     ExitBlock = createBasicBlock("for.cond.cleanup");
919 
920   // The loop body, consisting of the specified body and the loop variable.
921   llvm::BasicBlock *ForBody = createBasicBlock("for.body");
922 
923   // The body is executed if the expression, contextually converted
924   // to bool, is true.
925   llvm::Value *BoolCondVal = EvaluateExprAsBool(S.getCond());
926   llvm::BranchInst *CondBr = Builder.CreateCondBr(
927       BoolCondVal, ForBody, ExitBlock, PGO.createLoopWeights(S.getCond(), Cnt));
928 
929   // Attach metadata to loop body conditional branch.
930   EmitCondBrHints(ForBody->getContext(), CondBr, ForAttrs);
931 
932   if (ExitBlock != LoopExit.getBlock()) {
933     EmitBlock(ExitBlock);
934     EmitBranchThroughCleanup(LoopExit);
935   }
936 
937   EmitBlock(ForBody);
938   Cnt.beginRegion(Builder);
939 
940   // Create a block for the increment. In case of a 'continue', we jump there.
941   JumpDest Continue = getJumpDestInCurrentScope("for.inc");
942 
943   // Store the blocks to use for break and continue.
944   BreakContinueStack.push_back(BreakContinue(LoopExit, Continue));
945 
946   {
947     // Create a separate cleanup scope for the loop variable and body.
948     RunCleanupsScope BodyScope(*this);
949     EmitStmt(S.getLoopVarStmt());
950     EmitStmt(S.getBody());
951   }
952 
953   // If there is an increment, emit it next.
954   EmitBlock(Continue.getBlock());
955   EmitStmt(S.getInc());
956 
957   BreakContinueStack.pop_back();
958 
959   EmitBranch(CondBlock);
960 
961   ForScope.ForceCleanup();
962 
963   if (DI)
964     DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
965 
966   LoopStack.pop();
967 
968   // Emit the fall-through block.
969   EmitBlock(LoopExit.getBlock(), true);
970 }
971 
972 void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
973   if (RV.isScalar()) {
974     Builder.CreateStore(RV.getScalarVal(), ReturnValue);
975   } else if (RV.isAggregate()) {
976     EmitAggregateCopy(ReturnValue, RV.getAggregateAddr(), Ty);
977   } else {
978     EmitStoreOfComplex(RV.getComplexVal(),
979                        MakeNaturalAlignAddrLValue(ReturnValue, Ty),
980                        /*init*/ true);
981   }
982   EmitBranchThroughCleanup(ReturnBlock);
983 }
984 
985 /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand
986 /// if the function returns void, or may be missing one if the function returns
987 /// non-void.  Fun stuff :).
988 void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
989   // Emit the result value, even if unused, to evalute the side effects.
990   const Expr *RV = S.getRetValue();
991 
992   // Treat block literals in a return expression as if they appeared
993   // in their own scope.  This permits a small, easily-implemented
994   // exception to our over-conservative rules about not jumping to
995   // statements following block literals with non-trivial cleanups.
996   RunCleanupsScope cleanupScope(*this);
997   if (const ExprWithCleanups *cleanups =
998         dyn_cast_or_null<ExprWithCleanups>(RV)) {
999     enterFullExpression(cleanups);
1000     RV = cleanups->getSubExpr();
1001   }
1002 
1003   // FIXME: Clean this up by using an LValue for ReturnTemp,
1004   // EmitStoreThroughLValue, and EmitAnyExpr.
1005   if (getLangOpts().ElideConstructors &&
1006       S.getNRVOCandidate() && S.getNRVOCandidate()->isNRVOVariable()) {
1007     // Apply the named return value optimization for this return statement,
1008     // which means doing nothing: the appropriate result has already been
1009     // constructed into the NRVO variable.
1010 
1011     // If there is an NRVO flag for this variable, set it to 1 into indicate
1012     // that the cleanup code should not destroy the variable.
1013     if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()])
1014       Builder.CreateStore(Builder.getTrue(), NRVOFlag);
1015   } else if (!ReturnValue || (RV && RV->getType()->isVoidType())) {
1016     // Make sure not to return anything, but evaluate the expression
1017     // for side effects.
1018     if (RV)
1019       EmitAnyExpr(RV);
1020   } else if (!RV) {
1021     // Do nothing (return value is left uninitialized)
1022   } else if (FnRetTy->isReferenceType()) {
1023     // If this function returns a reference, take the address of the expression
1024     // rather than the value.
1025     RValue Result = EmitReferenceBindingToExpr(RV);
1026     Builder.CreateStore(Result.getScalarVal(), ReturnValue);
1027   } else {
1028     switch (getEvaluationKind(RV->getType())) {
1029     case TEK_Scalar:
1030       Builder.CreateStore(EmitScalarExpr(RV), ReturnValue);
1031       break;
1032     case TEK_Complex:
1033       EmitComplexExprIntoLValue(RV,
1034                      MakeNaturalAlignAddrLValue(ReturnValue, RV->getType()),
1035                                 /*isInit*/ true);
1036       break;
1037     case TEK_Aggregate: {
1038       CharUnits Alignment = getContext().getTypeAlignInChars(RV->getType());
1039       EmitAggExpr(RV, AggValueSlot::forAddr(ReturnValue, Alignment,
1040                                             Qualifiers(),
1041                                             AggValueSlot::IsDestructed,
1042                                             AggValueSlot::DoesNotNeedGCBarriers,
1043                                             AggValueSlot::IsNotAliased));
1044       break;
1045     }
1046     }
1047   }
1048 
1049   ++NumReturnExprs;
1050   if (!RV || RV->isEvaluatable(getContext()))
1051     ++NumSimpleReturnExprs;
1052 
1053   cleanupScope.ForceCleanup();
1054   EmitBranchThroughCleanup(ReturnBlock);
1055 }
1056 
1057 void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) {
1058   // As long as debug info is modeled with instructions, we have to ensure we
1059   // have a place to insert here and write the stop point here.
1060   if (HaveInsertPoint())
1061     EmitStopPoint(&S);
1062 
1063   for (const auto *I : S.decls())
1064     EmitDecl(*I);
1065 }
1066 
1067 void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) {
1068   assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!");
1069 
1070   // If this code is reachable then emit a stop point (if generating
1071   // debug info). We have to do this ourselves because we are on the
1072   // "simple" statement path.
1073   if (HaveInsertPoint())
1074     EmitStopPoint(&S);
1075 
1076   EmitBranchThroughCleanup(BreakContinueStack.back().BreakBlock);
1077 }
1078 
1079 void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) {
1080   assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1081 
1082   // If this code is reachable then emit a stop point (if generating
1083   // debug info). We have to do this ourselves because we are on the
1084   // "simple" statement path.
1085   if (HaveInsertPoint())
1086     EmitStopPoint(&S);
1087 
1088   EmitBranchThroughCleanup(BreakContinueStack.back().ContinueBlock);
1089 }
1090 
1091 /// EmitCaseStmtRange - If case statement range is not too big then
1092 /// add multiple cases to switch instruction, one for each value within
1093 /// the range. If range is too big then emit "if" condition check.
1094 void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S) {
1095   assert(S.getRHS() && "Expected RHS value in CaseStmt");
1096 
1097   llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(getContext());
1098   llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(getContext());
1099 
1100   RegionCounter CaseCnt = getPGORegionCounter(&S);
1101 
1102   // Emit the code for this case. We do this first to make sure it is
1103   // properly chained from our predecessor before generating the
1104   // switch machinery to enter this block.
1105   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1106   EmitBlockWithFallThrough(CaseDest, CaseCnt);
1107   EmitStmt(S.getSubStmt());
1108 
1109   // If range is empty, do nothing.
1110   if (LHS.isSigned() ? RHS.slt(LHS) : RHS.ult(LHS))
1111     return;
1112 
1113   llvm::APInt Range = RHS - LHS;
1114   // FIXME: parameters such as this should not be hardcoded.
1115   if (Range.ult(llvm::APInt(Range.getBitWidth(), 64))) {
1116     // Range is small enough to add multiple switch instruction cases.
1117     uint64_t Total = CaseCnt.getCount();
1118     unsigned NCases = Range.getZExtValue() + 1;
1119     // We only have one region counter for the entire set of cases here, so we
1120     // need to divide the weights evenly between the generated cases, ensuring
1121     // that the total weight is preserved. E.g., a weight of 5 over three cases
1122     // will be distributed as weights of 2, 2, and 1.
1123     uint64_t Weight = Total / NCases, Rem = Total % NCases;
1124     for (unsigned I = 0; I != NCases; ++I) {
1125       if (SwitchWeights)
1126         SwitchWeights->push_back(Weight + (Rem ? 1 : 0));
1127       if (Rem)
1128         Rem--;
1129       SwitchInsn->addCase(Builder.getInt(LHS), CaseDest);
1130       LHS++;
1131     }
1132     return;
1133   }
1134 
1135   // The range is too big. Emit "if" condition into a new block,
1136   // making sure to save and restore the current insertion point.
1137   llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock();
1138 
1139   // Push this test onto the chain of range checks (which terminates
1140   // in the default basic block). The switch's default will be changed
1141   // to the top of this chain after switch emission is complete.
1142   llvm::BasicBlock *FalseDest = CaseRangeBlock;
1143   CaseRangeBlock = createBasicBlock("sw.caserange");
1144 
1145   CurFn->getBasicBlockList().push_back(CaseRangeBlock);
1146   Builder.SetInsertPoint(CaseRangeBlock);
1147 
1148   // Emit range check.
1149   llvm::Value *Diff =
1150     Builder.CreateSub(SwitchInsn->getCondition(), Builder.getInt(LHS));
1151   llvm::Value *Cond =
1152     Builder.CreateICmpULE(Diff, Builder.getInt(Range), "inbounds");
1153 
1154   llvm::MDNode *Weights = nullptr;
1155   if (SwitchWeights) {
1156     uint64_t ThisCount = CaseCnt.getCount();
1157     uint64_t DefaultCount = (*SwitchWeights)[0];
1158     Weights = PGO.createBranchWeights(ThisCount, DefaultCount);
1159 
1160     // Since we're chaining the switch default through each large case range, we
1161     // need to update the weight for the default, ie, the first case, to include
1162     // this case.
1163     (*SwitchWeights)[0] += ThisCount;
1164   }
1165   Builder.CreateCondBr(Cond, CaseDest, FalseDest, Weights);
1166 
1167   // Restore the appropriate insertion point.
1168   if (RestoreBB)
1169     Builder.SetInsertPoint(RestoreBB);
1170   else
1171     Builder.ClearInsertionPoint();
1172 }
1173 
1174 void CodeGenFunction::EmitCaseStmt(const CaseStmt &S) {
1175   // If there is no enclosing switch instance that we're aware of, then this
1176   // case statement and its block can be elided.  This situation only happens
1177   // when we've constant-folded the switch, are emitting the constant case,
1178   // and part of the constant case includes another case statement.  For
1179   // instance: switch (4) { case 4: do { case 5: } while (1); }
1180   if (!SwitchInsn) {
1181     EmitStmt(S.getSubStmt());
1182     return;
1183   }
1184 
1185   // Handle case ranges.
1186   if (S.getRHS()) {
1187     EmitCaseStmtRange(S);
1188     return;
1189   }
1190 
1191   RegionCounter CaseCnt = getPGORegionCounter(&S);
1192   llvm::ConstantInt *CaseVal =
1193     Builder.getInt(S.getLHS()->EvaluateKnownConstInt(getContext()));
1194 
1195   // If the body of the case is just a 'break', try to not emit an empty block.
1196   // If we're profiling or we're not optimizing, leave the block in for better
1197   // debug and coverage analysis.
1198   if (!CGM.getCodeGenOpts().ProfileInstrGenerate &&
1199       CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1200       isa<BreakStmt>(S.getSubStmt())) {
1201     JumpDest Block = BreakContinueStack.back().BreakBlock;
1202 
1203     // Only do this optimization if there are no cleanups that need emitting.
1204     if (isObviouslyBranchWithoutCleanups(Block)) {
1205       if (SwitchWeights)
1206         SwitchWeights->push_back(CaseCnt.getCount());
1207       SwitchInsn->addCase(CaseVal, Block.getBlock());
1208 
1209       // If there was a fallthrough into this case, make sure to redirect it to
1210       // the end of the switch as well.
1211       if (Builder.GetInsertBlock()) {
1212         Builder.CreateBr(Block.getBlock());
1213         Builder.ClearInsertionPoint();
1214       }
1215       return;
1216     }
1217   }
1218 
1219   llvm::BasicBlock *CaseDest = createBasicBlock("sw.bb");
1220   EmitBlockWithFallThrough(CaseDest, CaseCnt);
1221   if (SwitchWeights)
1222     SwitchWeights->push_back(CaseCnt.getCount());
1223   SwitchInsn->addCase(CaseVal, CaseDest);
1224 
1225   // Recursively emitting the statement is acceptable, but is not wonderful for
1226   // code where we have many case statements nested together, i.e.:
1227   //  case 1:
1228   //    case 2:
1229   //      case 3: etc.
1230   // Handling this recursively will create a new block for each case statement
1231   // that falls through to the next case which is IR intensive.  It also causes
1232   // deep recursion which can run into stack depth limitations.  Handle
1233   // sequential non-range case statements specially.
1234   const CaseStmt *CurCase = &S;
1235   const CaseStmt *NextCase = dyn_cast<CaseStmt>(S.getSubStmt());
1236 
1237   // Otherwise, iteratively add consecutive cases to this switch stmt.
1238   while (NextCase && NextCase->getRHS() == nullptr) {
1239     CurCase = NextCase;
1240     llvm::ConstantInt *CaseVal =
1241       Builder.getInt(CurCase->getLHS()->EvaluateKnownConstInt(getContext()));
1242 
1243     CaseCnt = getPGORegionCounter(NextCase);
1244     if (SwitchWeights)
1245       SwitchWeights->push_back(CaseCnt.getCount());
1246     if (CGM.getCodeGenOpts().ProfileInstrGenerate) {
1247       CaseDest = createBasicBlock("sw.bb");
1248       EmitBlockWithFallThrough(CaseDest, CaseCnt);
1249     }
1250 
1251     SwitchInsn->addCase(CaseVal, CaseDest);
1252     NextCase = dyn_cast<CaseStmt>(CurCase->getSubStmt());
1253   }
1254 
1255   // Normal default recursion for non-cases.
1256   EmitStmt(CurCase->getSubStmt());
1257 }
1258 
1259 void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S) {
1260   llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest();
1261   assert(DefaultBlock->empty() &&
1262          "EmitDefaultStmt: Default block already defined?");
1263 
1264   RegionCounter Cnt = getPGORegionCounter(&S);
1265   EmitBlockWithFallThrough(DefaultBlock, Cnt);
1266 
1267   EmitStmt(S.getSubStmt());
1268 }
1269 
1270 /// CollectStatementsForCase - Given the body of a 'switch' statement and a
1271 /// constant value that is being switched on, see if we can dead code eliminate
1272 /// the body of the switch to a simple series of statements to emit.  Basically,
1273 /// on a switch (5) we want to find these statements:
1274 ///    case 5:
1275 ///      printf(...);    <--
1276 ///      ++i;            <--
1277 ///      break;
1278 ///
1279 /// and add them to the ResultStmts vector.  If it is unsafe to do this
1280 /// transformation (for example, one of the elided statements contains a label
1281 /// that might be jumped to), return CSFC_Failure.  If we handled it and 'S'
1282 /// should include statements after it (e.g. the printf() line is a substmt of
1283 /// the case) then return CSFC_FallThrough.  If we handled it and found a break
1284 /// statement, then return CSFC_Success.
1285 ///
1286 /// If Case is non-null, then we are looking for the specified case, checking
1287 /// that nothing we jump over contains labels.  If Case is null, then we found
1288 /// the case and are looking for the break.
1289 ///
1290 /// If the recursive walk actually finds our Case, then we set FoundCase to
1291 /// true.
1292 ///
1293 enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success };
1294 static CSFC_Result CollectStatementsForCase(const Stmt *S,
1295                                             const SwitchCase *Case,
1296                                             bool &FoundCase,
1297                               SmallVectorImpl<const Stmt*> &ResultStmts) {
1298   // If this is a null statement, just succeed.
1299   if (!S)
1300     return Case ? CSFC_Success : CSFC_FallThrough;
1301 
1302   // If this is the switchcase (case 4: or default) that we're looking for, then
1303   // we're in business.  Just add the substatement.
1304   if (const SwitchCase *SC = dyn_cast<SwitchCase>(S)) {
1305     if (S == Case) {
1306       FoundCase = true;
1307       return CollectStatementsForCase(SC->getSubStmt(), nullptr, FoundCase,
1308                                       ResultStmts);
1309     }
1310 
1311     // Otherwise, this is some other case or default statement, just ignore it.
1312     return CollectStatementsForCase(SC->getSubStmt(), Case, FoundCase,
1313                                     ResultStmts);
1314   }
1315 
1316   // If we are in the live part of the code and we found our break statement,
1317   // return a success!
1318   if (!Case && isa<BreakStmt>(S))
1319     return CSFC_Success;
1320 
1321   // If this is a switch statement, then it might contain the SwitchCase, the
1322   // break, or neither.
1323   if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1324     // Handle this as two cases: we might be looking for the SwitchCase (if so
1325     // the skipped statements must be skippable) or we might already have it.
1326     CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end();
1327     if (Case) {
1328       // Keep track of whether we see a skipped declaration.  The code could be
1329       // using the declaration even if it is skipped, so we can't optimize out
1330       // the decl if the kept statements might refer to it.
1331       bool HadSkippedDecl = false;
1332 
1333       // If we're looking for the case, just see if we can skip each of the
1334       // substatements.
1335       for (; Case && I != E; ++I) {
1336         HadSkippedDecl |= isa<DeclStmt>(*I);
1337 
1338         switch (CollectStatementsForCase(*I, Case, FoundCase, ResultStmts)) {
1339         case CSFC_Failure: return CSFC_Failure;
1340         case CSFC_Success:
1341           // A successful result means that either 1) that the statement doesn't
1342           // have the case and is skippable, or 2) does contain the case value
1343           // and also contains the break to exit the switch.  In the later case,
1344           // we just verify the rest of the statements are elidable.
1345           if (FoundCase) {
1346             // If we found the case and skipped declarations, we can't do the
1347             // optimization.
1348             if (HadSkippedDecl)
1349               return CSFC_Failure;
1350 
1351             for (++I; I != E; ++I)
1352               if (CodeGenFunction::ContainsLabel(*I, true))
1353                 return CSFC_Failure;
1354             return CSFC_Success;
1355           }
1356           break;
1357         case CSFC_FallThrough:
1358           // If we have a fallthrough condition, then we must have found the
1359           // case started to include statements.  Consider the rest of the
1360           // statements in the compound statement as candidates for inclusion.
1361           assert(FoundCase && "Didn't find case but returned fallthrough?");
1362           // We recursively found Case, so we're not looking for it anymore.
1363           Case = nullptr;
1364 
1365           // If we found the case and skipped declarations, we can't do the
1366           // optimization.
1367           if (HadSkippedDecl)
1368             return CSFC_Failure;
1369           break;
1370         }
1371       }
1372     }
1373 
1374     // If we have statements in our range, then we know that the statements are
1375     // live and need to be added to the set of statements we're tracking.
1376     for (; I != E; ++I) {
1377       switch (CollectStatementsForCase(*I, nullptr, FoundCase, ResultStmts)) {
1378       case CSFC_Failure: return CSFC_Failure;
1379       case CSFC_FallThrough:
1380         // A fallthrough result means that the statement was simple and just
1381         // included in ResultStmt, keep adding them afterwards.
1382         break;
1383       case CSFC_Success:
1384         // A successful result means that we found the break statement and
1385         // stopped statement inclusion.  We just ensure that any leftover stmts
1386         // are skippable and return success ourselves.
1387         for (++I; I != E; ++I)
1388           if (CodeGenFunction::ContainsLabel(*I, true))
1389             return CSFC_Failure;
1390         return CSFC_Success;
1391       }
1392     }
1393 
1394     return Case ? CSFC_Success : CSFC_FallThrough;
1395   }
1396 
1397   // Okay, this is some other statement that we don't handle explicitly, like a
1398   // for statement or increment etc.  If we are skipping over this statement,
1399   // just verify it doesn't have labels, which would make it invalid to elide.
1400   if (Case) {
1401     if (CodeGenFunction::ContainsLabel(S, true))
1402       return CSFC_Failure;
1403     return CSFC_Success;
1404   }
1405 
1406   // Otherwise, we want to include this statement.  Everything is cool with that
1407   // so long as it doesn't contain a break out of the switch we're in.
1408   if (CodeGenFunction::containsBreak(S)) return CSFC_Failure;
1409 
1410   // Otherwise, everything is great.  Include the statement and tell the caller
1411   // that we fall through and include the next statement as well.
1412   ResultStmts.push_back(S);
1413   return CSFC_FallThrough;
1414 }
1415 
1416 /// FindCaseStatementsForValue - Find the case statement being jumped to and
1417 /// then invoke CollectStatementsForCase to find the list of statements to emit
1418 /// for a switch on constant.  See the comment above CollectStatementsForCase
1419 /// for more details.
1420 static bool FindCaseStatementsForValue(const SwitchStmt &S,
1421                                        const llvm::APSInt &ConstantCondValue,
1422                                 SmallVectorImpl<const Stmt*> &ResultStmts,
1423                                        ASTContext &C,
1424                                        const SwitchCase *&ResultCase) {
1425   // First step, find the switch case that is being branched to.  We can do this
1426   // efficiently by scanning the SwitchCase list.
1427   const SwitchCase *Case = S.getSwitchCaseList();
1428   const DefaultStmt *DefaultCase = nullptr;
1429 
1430   for (; Case; Case = Case->getNextSwitchCase()) {
1431     // It's either a default or case.  Just remember the default statement in
1432     // case we're not jumping to any numbered cases.
1433     if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Case)) {
1434       DefaultCase = DS;
1435       continue;
1436     }
1437 
1438     // Check to see if this case is the one we're looking for.
1439     const CaseStmt *CS = cast<CaseStmt>(Case);
1440     // Don't handle case ranges yet.
1441     if (CS->getRHS()) return false;
1442 
1443     // If we found our case, remember it as 'case'.
1444     if (CS->getLHS()->EvaluateKnownConstInt(C) == ConstantCondValue)
1445       break;
1446   }
1447 
1448   // If we didn't find a matching case, we use a default if it exists, or we
1449   // elide the whole switch body!
1450   if (!Case) {
1451     // It is safe to elide the body of the switch if it doesn't contain labels
1452     // etc.  If it is safe, return successfully with an empty ResultStmts list.
1453     if (!DefaultCase)
1454       return !CodeGenFunction::ContainsLabel(&S);
1455     Case = DefaultCase;
1456   }
1457 
1458   // Ok, we know which case is being jumped to, try to collect all the
1459   // statements that follow it.  This can fail for a variety of reasons.  Also,
1460   // check to see that the recursive walk actually found our case statement.
1461   // Insane cases like this can fail to find it in the recursive walk since we
1462   // don't handle every stmt kind:
1463   // switch (4) {
1464   //   while (1) {
1465   //     case 4: ...
1466   bool FoundCase = false;
1467   ResultCase = Case;
1468   return CollectStatementsForCase(S.getBody(), Case, FoundCase,
1469                                   ResultStmts) != CSFC_Failure &&
1470          FoundCase;
1471 }
1472 
1473 void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) {
1474   // Handle nested switch statements.
1475   llvm::SwitchInst *SavedSwitchInsn = SwitchInsn;
1476   SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights;
1477   llvm::BasicBlock *SavedCRBlock = CaseRangeBlock;
1478 
1479   // See if we can constant fold the condition of the switch and therefore only
1480   // emit the live case statement (if any) of the switch.
1481   llvm::APSInt ConstantCondValue;
1482   if (ConstantFoldsToSimpleInteger(S.getCond(), ConstantCondValue)) {
1483     SmallVector<const Stmt*, 4> CaseStmts;
1484     const SwitchCase *Case = nullptr;
1485     if (FindCaseStatementsForValue(S, ConstantCondValue, CaseStmts,
1486                                    getContext(), Case)) {
1487       if (Case) {
1488         RegionCounter CaseCnt = getPGORegionCounter(Case);
1489         CaseCnt.beginRegion(Builder);
1490       }
1491       RunCleanupsScope ExecutedScope(*this);
1492 
1493       // Emit the condition variable if needed inside the entire cleanup scope
1494       // used by this special case for constant folded switches.
1495       if (S.getConditionVariable())
1496         EmitAutoVarDecl(*S.getConditionVariable());
1497 
1498       // At this point, we are no longer "within" a switch instance, so
1499       // we can temporarily enforce this to ensure that any embedded case
1500       // statements are not emitted.
1501       SwitchInsn = nullptr;
1502 
1503       // Okay, we can dead code eliminate everything except this case.  Emit the
1504       // specified series of statements and we're good.
1505       for (unsigned i = 0, e = CaseStmts.size(); i != e; ++i)
1506         EmitStmt(CaseStmts[i]);
1507       RegionCounter ExitCnt = getPGORegionCounter(&S);
1508       ExitCnt.beginRegion(Builder);
1509 
1510       // Now we want to restore the saved switch instance so that nested
1511       // switches continue to function properly
1512       SwitchInsn = SavedSwitchInsn;
1513 
1514       return;
1515     }
1516   }
1517 
1518   JumpDest SwitchExit = getJumpDestInCurrentScope("sw.epilog");
1519 
1520   RunCleanupsScope ConditionScope(*this);
1521   if (S.getConditionVariable())
1522     EmitAutoVarDecl(*S.getConditionVariable());
1523   llvm::Value *CondV = EmitScalarExpr(S.getCond());
1524 
1525   // Create basic block to hold stuff that comes after switch
1526   // statement. We also need to create a default block now so that
1527   // explicit case ranges tests can have a place to jump to on
1528   // failure.
1529   llvm::BasicBlock *DefaultBlock = createBasicBlock("sw.default");
1530   SwitchInsn = Builder.CreateSwitch(CondV, DefaultBlock);
1531   if (PGO.haveRegionCounts()) {
1532     // Walk the SwitchCase list to find how many there are.
1533     uint64_t DefaultCount = 0;
1534     unsigned NumCases = 0;
1535     for (const SwitchCase *Case = S.getSwitchCaseList();
1536          Case;
1537          Case = Case->getNextSwitchCase()) {
1538       if (isa<DefaultStmt>(Case))
1539         DefaultCount = getPGORegionCounter(Case).getCount();
1540       NumCases += 1;
1541     }
1542     SwitchWeights = new SmallVector<uint64_t, 16>();
1543     SwitchWeights->reserve(NumCases);
1544     // The default needs to be first. We store the edge count, so we already
1545     // know the right weight.
1546     SwitchWeights->push_back(DefaultCount);
1547   }
1548   CaseRangeBlock = DefaultBlock;
1549 
1550   // Clear the insertion point to indicate we are in unreachable code.
1551   Builder.ClearInsertionPoint();
1552 
1553   // All break statements jump to NextBlock. If BreakContinueStack is non-empty
1554   // then reuse last ContinueBlock.
1555   JumpDest OuterContinue;
1556   if (!BreakContinueStack.empty())
1557     OuterContinue = BreakContinueStack.back().ContinueBlock;
1558 
1559   BreakContinueStack.push_back(BreakContinue(SwitchExit, OuterContinue));
1560 
1561   // Emit switch body.
1562   EmitStmt(S.getBody());
1563 
1564   BreakContinueStack.pop_back();
1565 
1566   // Update the default block in case explicit case range tests have
1567   // been chained on top.
1568   SwitchInsn->setDefaultDest(CaseRangeBlock);
1569 
1570   // If a default was never emitted:
1571   if (!DefaultBlock->getParent()) {
1572     // If we have cleanups, emit the default block so that there's a
1573     // place to jump through the cleanups from.
1574     if (ConditionScope.requiresCleanups()) {
1575       EmitBlock(DefaultBlock);
1576 
1577     // Otherwise, just forward the default block to the switch end.
1578     } else {
1579       DefaultBlock->replaceAllUsesWith(SwitchExit.getBlock());
1580       delete DefaultBlock;
1581     }
1582   }
1583 
1584   ConditionScope.ForceCleanup();
1585 
1586   // Emit continuation.
1587   EmitBlock(SwitchExit.getBlock(), true);
1588   RegionCounter ExitCnt = getPGORegionCounter(&S);
1589   ExitCnt.beginRegion(Builder);
1590 
1591   if (SwitchWeights) {
1592     assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() &&
1593            "switch weights do not match switch cases");
1594     // If there's only one jump destination there's no sense weighting it.
1595     if (SwitchWeights->size() > 1)
1596       SwitchInsn->setMetadata(llvm::LLVMContext::MD_prof,
1597                               PGO.createBranchWeights(*SwitchWeights));
1598     delete SwitchWeights;
1599   }
1600   SwitchInsn = SavedSwitchInsn;
1601   SwitchWeights = SavedSwitchWeights;
1602   CaseRangeBlock = SavedCRBlock;
1603 }
1604 
1605 static std::string
1606 SimplifyConstraint(const char *Constraint, const TargetInfo &Target,
1607                  SmallVectorImpl<TargetInfo::ConstraintInfo> *OutCons=nullptr) {
1608   std::string Result;
1609 
1610   while (*Constraint) {
1611     switch (*Constraint) {
1612     default:
1613       Result += Target.convertConstraint(Constraint);
1614       break;
1615     // Ignore these
1616     case '*':
1617     case '?':
1618     case '!':
1619     case '=': // Will see this and the following in mult-alt constraints.
1620     case '+':
1621       break;
1622     case '#': // Ignore the rest of the constraint alternative.
1623       while (Constraint[1] && Constraint[1] != ',')
1624         Constraint++;
1625       break;
1626     case ',':
1627       Result += "|";
1628       break;
1629     case 'g':
1630       Result += "imr";
1631       break;
1632     case '[': {
1633       assert(OutCons &&
1634              "Must pass output names to constraints with a symbolic name");
1635       unsigned Index;
1636       bool result = Target.resolveSymbolicName(Constraint,
1637                                                &(*OutCons)[0],
1638                                                OutCons->size(), Index);
1639       assert(result && "Could not resolve symbolic name"); (void)result;
1640       Result += llvm::utostr(Index);
1641       break;
1642     }
1643     }
1644 
1645     Constraint++;
1646   }
1647 
1648   return Result;
1649 }
1650 
1651 /// AddVariableConstraints - Look at AsmExpr and if it is a variable declared
1652 /// as using a particular register add that as a constraint that will be used
1653 /// in this asm stmt.
1654 static std::string
1655 AddVariableConstraints(const std::string &Constraint, const Expr &AsmExpr,
1656                        const TargetInfo &Target, CodeGenModule &CGM,
1657                        const AsmStmt &Stmt) {
1658   const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(&AsmExpr);
1659   if (!AsmDeclRef)
1660     return Constraint;
1661   const ValueDecl &Value = *AsmDeclRef->getDecl();
1662   const VarDecl *Variable = dyn_cast<VarDecl>(&Value);
1663   if (!Variable)
1664     return Constraint;
1665   if (Variable->getStorageClass() != SC_Register)
1666     return Constraint;
1667   AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
1668   if (!Attr)
1669     return Constraint;
1670   StringRef Register = Attr->getLabel();
1671   assert(Target.isValidGCCRegisterName(Register));
1672   // We're using validateOutputConstraint here because we only care if
1673   // this is a register constraint.
1674   TargetInfo::ConstraintInfo Info(Constraint, "");
1675   if (Target.validateOutputConstraint(Info) &&
1676       !Info.allowsRegister()) {
1677     CGM.ErrorUnsupported(&Stmt, "__asm__");
1678     return Constraint;
1679   }
1680   // Canonicalize the register here before returning it.
1681   Register = Target.getNormalizedGCCRegisterName(Register);
1682   return "{" + Register.str() + "}";
1683 }
1684 
1685 llvm::Value*
1686 CodeGenFunction::EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
1687                                     LValue InputValue, QualType InputType,
1688                                     std::string &ConstraintStr,
1689                                     SourceLocation Loc) {
1690   llvm::Value *Arg;
1691   if (Info.allowsRegister() || !Info.allowsMemory()) {
1692     if (CodeGenFunction::hasScalarEvaluationKind(InputType)) {
1693       Arg = EmitLoadOfLValue(InputValue, Loc).getScalarVal();
1694     } else {
1695       llvm::Type *Ty = ConvertType(InputType);
1696       uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty);
1697       if (Size <= 64 && llvm::isPowerOf2_64(Size)) {
1698         Ty = llvm::IntegerType::get(getLLVMContext(), Size);
1699         Ty = llvm::PointerType::getUnqual(Ty);
1700 
1701         Arg = Builder.CreateLoad(Builder.CreateBitCast(InputValue.getAddress(),
1702                                                        Ty));
1703       } else {
1704         Arg = InputValue.getAddress();
1705         ConstraintStr += '*';
1706       }
1707     }
1708   } else {
1709     Arg = InputValue.getAddress();
1710     ConstraintStr += '*';
1711   }
1712 
1713   return Arg;
1714 }
1715 
1716 llvm::Value* CodeGenFunction::EmitAsmInput(
1717                                          const TargetInfo::ConstraintInfo &Info,
1718                                            const Expr *InputExpr,
1719                                            std::string &ConstraintStr) {
1720   if (Info.allowsRegister() || !Info.allowsMemory())
1721     if (CodeGenFunction::hasScalarEvaluationKind(InputExpr->getType()))
1722       return EmitScalarExpr(InputExpr);
1723 
1724   InputExpr = InputExpr->IgnoreParenNoopCasts(getContext());
1725   LValue Dest = EmitLValue(InputExpr);
1726   return EmitAsmInputLValue(Info, Dest, InputExpr->getType(), ConstraintStr,
1727                             InputExpr->getExprLoc());
1728 }
1729 
1730 /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline
1731 /// asm call instruction.  The !srcloc MDNode contains a list of constant
1732 /// integers which are the source locations of the start of each line in the
1733 /// asm.
1734 static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
1735                                       CodeGenFunction &CGF) {
1736   SmallVector<llvm::Value *, 8> Locs;
1737   // Add the location of the first line to the MDNode.
1738   Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1739                                         Str->getLocStart().getRawEncoding()));
1740   StringRef StrVal = Str->getString();
1741   if (!StrVal.empty()) {
1742     const SourceManager &SM = CGF.CGM.getContext().getSourceManager();
1743     const LangOptions &LangOpts = CGF.CGM.getLangOpts();
1744 
1745     // Add the location of the start of each subsequent line of the asm to the
1746     // MDNode.
1747     for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
1748       if (StrVal[i] != '\n') continue;
1749       SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
1750                                                       CGF.getTarget());
1751       Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
1752                                             LineLoc.getRawEncoding()));
1753     }
1754   }
1755 
1756   return llvm::MDNode::get(CGF.getLLVMContext(), Locs);
1757 }
1758 
1759 void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
1760   // Assemble the final asm string.
1761   std::string AsmString = S.generateAsmString(getContext());
1762 
1763   // Get all the output and input constraints together.
1764   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1765   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1766 
1767   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1768     StringRef Name;
1769     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1770       Name = GAS->getOutputName(i);
1771     TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
1772     bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
1773     assert(IsValid && "Failed to parse output constraint");
1774     OutputConstraintInfos.push_back(Info);
1775   }
1776 
1777   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1778     StringRef Name;
1779     if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
1780       Name = GAS->getInputName(i);
1781     TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
1782     bool IsValid =
1783       getTarget().validateInputConstraint(OutputConstraintInfos.data(),
1784                                           S.getNumOutputs(), Info);
1785     assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
1786     InputConstraintInfos.push_back(Info);
1787   }
1788 
1789   std::string Constraints;
1790 
1791   std::vector<LValue> ResultRegDests;
1792   std::vector<QualType> ResultRegQualTys;
1793   std::vector<llvm::Type *> ResultRegTypes;
1794   std::vector<llvm::Type *> ResultTruncRegTypes;
1795   std::vector<llvm::Type *> ArgTypes;
1796   std::vector<llvm::Value*> Args;
1797 
1798   // Keep track of inout constraints.
1799   std::string InOutConstraints;
1800   std::vector<llvm::Value*> InOutArgs;
1801   std::vector<llvm::Type*> InOutArgTypes;
1802 
1803   for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
1804     TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
1805 
1806     // Simplify the output constraint.
1807     std::string OutputConstraint(S.getOutputConstraint(i));
1808     OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
1809                                           getTarget());
1810 
1811     const Expr *OutExpr = S.getOutputExpr(i);
1812     OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
1813 
1814     OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
1815                                               getTarget(), CGM, S);
1816 
1817     LValue Dest = EmitLValue(OutExpr);
1818     if (!Constraints.empty())
1819       Constraints += ',';
1820 
1821     // If this is a register output, then make the inline asm return it
1822     // by-value.  If this is a memory result, return the value by-reference.
1823     if (!Info.allowsMemory() && hasScalarEvaluationKind(OutExpr->getType())) {
1824       Constraints += "=" + OutputConstraint;
1825       ResultRegQualTys.push_back(OutExpr->getType());
1826       ResultRegDests.push_back(Dest);
1827       ResultRegTypes.push_back(ConvertTypeForMem(OutExpr->getType()));
1828       ResultTruncRegTypes.push_back(ResultRegTypes.back());
1829 
1830       // If this output is tied to an input, and if the input is larger, then
1831       // we need to set the actual result type of the inline asm node to be the
1832       // same as the input type.
1833       if (Info.hasMatchingInput()) {
1834         unsigned InputNo;
1835         for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) {
1836           TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo];
1837           if (Input.hasTiedOperand() && Input.getTiedOperand() == i)
1838             break;
1839         }
1840         assert(InputNo != S.getNumInputs() && "Didn't find matching input!");
1841 
1842         QualType InputTy = S.getInputExpr(InputNo)->getType();
1843         QualType OutputType = OutExpr->getType();
1844 
1845         uint64_t InputSize = getContext().getTypeSize(InputTy);
1846         if (getContext().getTypeSize(OutputType) < InputSize) {
1847           // Form the asm to return the value as a larger integer or fp type.
1848           ResultRegTypes.back() = ConvertType(InputTy);
1849         }
1850       }
1851       if (llvm::Type* AdjTy =
1852             getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1853                                                  ResultRegTypes.back()))
1854         ResultRegTypes.back() = AdjTy;
1855       else {
1856         CGM.getDiags().Report(S.getAsmLoc(),
1857                               diag::err_asm_invalid_type_in_input)
1858             << OutExpr->getType() << OutputConstraint;
1859       }
1860     } else {
1861       ArgTypes.push_back(Dest.getAddress()->getType());
1862       Args.push_back(Dest.getAddress());
1863       Constraints += "=*";
1864       Constraints += OutputConstraint;
1865     }
1866 
1867     if (Info.isReadWrite()) {
1868       InOutConstraints += ',';
1869 
1870       const Expr *InputExpr = S.getOutputExpr(i);
1871       llvm::Value *Arg = EmitAsmInputLValue(Info, Dest, InputExpr->getType(),
1872                                             InOutConstraints,
1873                                             InputExpr->getExprLoc());
1874 
1875       if (llvm::Type* AdjTy =
1876           getTargetHooks().adjustInlineAsmType(*this, OutputConstraint,
1877                                                Arg->getType()))
1878         Arg = Builder.CreateBitCast(Arg, AdjTy);
1879 
1880       if (Info.allowsRegister())
1881         InOutConstraints += llvm::utostr(i);
1882       else
1883         InOutConstraints += OutputConstraint;
1884 
1885       InOutArgTypes.push_back(Arg->getType());
1886       InOutArgs.push_back(Arg);
1887     }
1888   }
1889 
1890   unsigned NumConstraints = S.getNumOutputs() + S.getNumInputs();
1891 
1892   for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
1893     const Expr *InputExpr = S.getInputExpr(i);
1894 
1895     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1896 
1897     if (!Constraints.empty())
1898       Constraints += ',';
1899 
1900     // Simplify the input constraint.
1901     std::string InputConstraint(S.getInputConstraint(i));
1902     InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
1903                                          &OutputConstraintInfos);
1904 
1905     InputConstraint =
1906       AddVariableConstraints(InputConstraint,
1907                             *InputExpr->IgnoreParenNoopCasts(getContext()),
1908                             getTarget(), CGM, S);
1909 
1910     llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
1911 
1912     // If this input argument is tied to a larger output result, extend the
1913     // input to be the same size as the output.  The LLVM backend wants to see
1914     // the input and output of a matching constraint be the same size.  Note
1915     // that GCC does not define what the top bits are here.  We use zext because
1916     // that is usually cheaper, but LLVM IR should really get an anyext someday.
1917     if (Info.hasTiedOperand()) {
1918       unsigned Output = Info.getTiedOperand();
1919       QualType OutputType = S.getOutputExpr(Output)->getType();
1920       QualType InputTy = InputExpr->getType();
1921 
1922       if (getContext().getTypeSize(OutputType) >
1923           getContext().getTypeSize(InputTy)) {
1924         // Use ptrtoint as appropriate so that we can do our extension.
1925         if (isa<llvm::PointerType>(Arg->getType()))
1926           Arg = Builder.CreatePtrToInt(Arg, IntPtrTy);
1927         llvm::Type *OutputTy = ConvertType(OutputType);
1928         if (isa<llvm::IntegerType>(OutputTy))
1929           Arg = Builder.CreateZExt(Arg, OutputTy);
1930         else if (isa<llvm::PointerType>(OutputTy))
1931           Arg = Builder.CreateZExt(Arg, IntPtrTy);
1932         else {
1933           assert(OutputTy->isFloatingPointTy() && "Unexpected output type");
1934           Arg = Builder.CreateFPExt(Arg, OutputTy);
1935         }
1936       }
1937     }
1938     if (llvm::Type* AdjTy =
1939               getTargetHooks().adjustInlineAsmType(*this, InputConstraint,
1940                                                    Arg->getType()))
1941       Arg = Builder.CreateBitCast(Arg, AdjTy);
1942     else
1943       CGM.getDiags().Report(S.getAsmLoc(), diag::err_asm_invalid_type_in_input)
1944           << InputExpr->getType() << InputConstraint;
1945 
1946     ArgTypes.push_back(Arg->getType());
1947     Args.push_back(Arg);
1948     Constraints += InputConstraint;
1949   }
1950 
1951   // Append the "input" part of inout constraints last.
1952   for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) {
1953     ArgTypes.push_back(InOutArgTypes[i]);
1954     Args.push_back(InOutArgs[i]);
1955   }
1956   Constraints += InOutConstraints;
1957 
1958   // Clobbers
1959   for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) {
1960     StringRef Clobber = S.getClobber(i);
1961 
1962     if (Clobber != "memory" && Clobber != "cc")
1963     Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
1964 
1965     if (i != 0 || NumConstraints != 0)
1966       Constraints += ',';
1967 
1968     Constraints += "~{";
1969     Constraints += Clobber;
1970     Constraints += '}';
1971   }
1972 
1973   // Add machine specific clobbers
1974   std::string MachineClobbers = getTarget().getClobbers();
1975   if (!MachineClobbers.empty()) {
1976     if (!Constraints.empty())
1977       Constraints += ',';
1978     Constraints += MachineClobbers;
1979   }
1980 
1981   llvm::Type *ResultType;
1982   if (ResultRegTypes.empty())
1983     ResultType = VoidTy;
1984   else if (ResultRegTypes.size() == 1)
1985     ResultType = ResultRegTypes[0];
1986   else
1987     ResultType = llvm::StructType::get(getLLVMContext(), ResultRegTypes);
1988 
1989   llvm::FunctionType *FTy =
1990     llvm::FunctionType::get(ResultType, ArgTypes, false);
1991 
1992   bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0;
1993   llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(&S) ?
1994     llvm::InlineAsm::AD_Intel : llvm::InlineAsm::AD_ATT;
1995   llvm::InlineAsm *IA =
1996     llvm::InlineAsm::get(FTy, AsmString, Constraints, HasSideEffect,
1997                          /* IsAlignStack */ false, AsmDialect);
1998   llvm::CallInst *Result = Builder.CreateCall(IA, Args);
1999   Result->addAttribute(llvm::AttributeSet::FunctionIndex,
2000                        llvm::Attribute::NoUnwind);
2001 
2002   // Slap the source location of the inline asm into a !srcloc metadata on the
2003   // call.  FIXME: Handle metadata for MS-style inline asms.
2004   if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(&S))
2005     Result->setMetadata("srcloc", getAsmSrcLocInfo(gccAsmStmt->getAsmString(),
2006                                                    *this));
2007 
2008   // Extract all of the register value results from the asm.
2009   std::vector<llvm::Value*> RegResults;
2010   if (ResultRegTypes.size() == 1) {
2011     RegResults.push_back(Result);
2012   } else {
2013     for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) {
2014       llvm::Value *Tmp = Builder.CreateExtractValue(Result, i, "asmresult");
2015       RegResults.push_back(Tmp);
2016     }
2017   }
2018 
2019   for (unsigned i = 0, e = RegResults.size(); i != e; ++i) {
2020     llvm::Value *Tmp = RegResults[i];
2021 
2022     // If the result type of the LLVM IR asm doesn't match the result type of
2023     // the expression, do the conversion.
2024     if (ResultRegTypes[i] != ResultTruncRegTypes[i]) {
2025       llvm::Type *TruncTy = ResultTruncRegTypes[i];
2026 
2027       // Truncate the integer result to the right size, note that TruncTy can be
2028       // a pointer.
2029       if (TruncTy->isFloatingPointTy())
2030         Tmp = Builder.CreateFPTrunc(Tmp, TruncTy);
2031       else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) {
2032         uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(TruncTy);
2033         Tmp = Builder.CreateTrunc(Tmp,
2034                    llvm::IntegerType::get(getLLVMContext(), (unsigned)ResSize));
2035         Tmp = Builder.CreateIntToPtr(Tmp, TruncTy);
2036       } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) {
2037         uint64_t TmpSize =CGM.getDataLayout().getTypeSizeInBits(Tmp->getType());
2038         Tmp = Builder.CreatePtrToInt(Tmp,
2039                    llvm::IntegerType::get(getLLVMContext(), (unsigned)TmpSize));
2040         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2041       } else if (TruncTy->isIntegerTy()) {
2042         Tmp = Builder.CreateTrunc(Tmp, TruncTy);
2043       } else if (TruncTy->isVectorTy()) {
2044         Tmp = Builder.CreateBitCast(Tmp, TruncTy);
2045       }
2046     }
2047 
2048     EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
2049   }
2050 }
2051 
2052 static LValue InitCapturedStruct(CodeGenFunction &CGF, const CapturedStmt &S) {
2053   const RecordDecl *RD = S.getCapturedRecordDecl();
2054   QualType RecordTy = CGF.getContext().getRecordType(RD);
2055 
2056   // Initialize the captured struct.
2057   LValue SlotLV = CGF.MakeNaturalAlignAddrLValue(
2058                     CGF.CreateMemTemp(RecordTy, "agg.captured"), RecordTy);
2059 
2060   RecordDecl::field_iterator CurField = RD->field_begin();
2061   for (CapturedStmt::capture_init_iterator I = S.capture_init_begin(),
2062                                            E = S.capture_init_end();
2063        I != E; ++I, ++CurField) {
2064     LValue LV = CGF.EmitLValueForFieldInitialization(SlotLV, *CurField);
2065     CGF.EmitInitializerForField(*CurField, LV, *I, ArrayRef<VarDecl *>());
2066   }
2067 
2068   return SlotLV;
2069 }
2070 
2071 static void InitVLACaptures(CodeGenFunction &CGF, const CapturedStmt &S) {
2072   for (auto &C : S.captures()) {
2073     if (C.capturesVariable()) {
2074       QualType QTy;
2075       auto VD = C.getCapturedVar();
2076       if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
2077         QTy = PVD->getOriginalType();
2078       else
2079         QTy = VD->getType();
2080       if (QTy->isVariablyModifiedType()) {
2081         CGF.EmitVariablyModifiedType(QTy);
2082       }
2083     }
2084   }
2085 }
2086 
2087 /// Generate an outlined function for the body of a CapturedStmt, store any
2088 /// captured variables into the captured struct, and call the outlined function.
2089 llvm::Function *
2090 CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) {
2091   LValue CapStruct = InitCapturedStruct(*this, S);
2092 
2093   // Emit the CapturedDecl
2094   CodeGenFunction CGF(CGM, true);
2095   CGF.CapturedStmtInfo = new CGCapturedStmtInfo(S, K);
2096   llvm::Function *F = CGF.GenerateCapturedStmtFunction(S);
2097   delete CGF.CapturedStmtInfo;
2098 
2099   // Emit call to the helper function.
2100   EmitCallOrInvoke(F, CapStruct.getAddress());
2101 
2102   return F;
2103 }
2104 
2105 llvm::Value *
2106 CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) {
2107   LValue CapStruct = InitCapturedStruct(*this, S);
2108   return CapStruct.getAddress();
2109 }
2110 
2111 /// Creates the outlined function for a CapturedStmt.
2112 llvm::Function *
2113 CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) {
2114   assert(CapturedStmtInfo &&
2115     "CapturedStmtInfo should be set when generating the captured function");
2116   const CapturedDecl *CD = S.getCapturedDecl();
2117   const RecordDecl *RD = S.getCapturedRecordDecl();
2118   SourceLocation Loc = S.getLocStart();
2119   assert(CD->hasBody() && "missing CapturedDecl body");
2120 
2121   // Build the argument list.
2122   ASTContext &Ctx = CGM.getContext();
2123   FunctionArgList Args;
2124   Args.append(CD->param_begin(), CD->param_end());
2125 
2126   // Create the function declaration.
2127   FunctionType::ExtInfo ExtInfo;
2128   const CGFunctionInfo &FuncInfo =
2129       CGM.getTypes().arrangeFreeFunctionDeclaration(Ctx.VoidTy, Args, ExtInfo,
2130                                                     /*IsVariadic=*/false);
2131   llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo);
2132 
2133   llvm::Function *F =
2134     llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage,
2135                            CapturedStmtInfo->getHelperName(), &CGM.getModule());
2136   CGM.SetInternalFunctionAttributes(CD, F, FuncInfo);
2137 
2138   // Generate the function.
2139   StartFunction(CD, Ctx.VoidTy, F, FuncInfo, Args,
2140                 CD->getLocation(),
2141                 CD->getBody()->getLocStart());
2142   // Set the context parameter in CapturedStmtInfo.
2143   llvm::Value *DeclPtr = LocalDeclMap[CD->getContextParam()];
2144   assert(DeclPtr && "missing context parameter for CapturedStmt");
2145   CapturedStmtInfo->setContextValue(Builder.CreateLoad(DeclPtr));
2146 
2147   // Initialize variable-length arrays.
2148   InitVLACaptures(*this, S);
2149 
2150   // If 'this' is captured, load it into CXXThisValue.
2151   if (CapturedStmtInfo->isCXXThisExprCaptured()) {
2152     FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl();
2153     LValue LV = MakeNaturalAlignAddrLValue(CapturedStmtInfo->getContextValue(),
2154                                            Ctx.getTagDeclType(RD));
2155     LValue ThisLValue = EmitLValueForField(LV, FD);
2156     CXXThisValue = EmitLoadOfLValue(ThisLValue, Loc).getScalarVal();
2157   }
2158 
2159   PGO.assignRegionCounters(CD, F);
2160   CapturedStmtInfo->EmitBody(*this, CD->getBody());
2161   FinishFunction(CD->getBodyRBrace());
2162   PGO.emitInstrumentationData();
2163   PGO.destroyRegionCounters();
2164 
2165   return F;
2166 }
2167