Make a distinction between 'outer' and 'inner' paths when binning.

Since libArachne treats _all_ outer walls, including holes, as index 0, then the next as index 2, etc. But if we want to print outside-in or inside-out, this represents a problem.

CURA-7557 CURA-7677

--- src/InsetOrderOptimizer.cpp
+++ src/InsetOrderOptimizer.cpp
@@ -633,19 +633,61 @@

 BinJunctions InsetOrderOptimizer::variableWidthPathToBinJunctions(const VariableWidthPaths& toolpaths)
 {
-    BinJunctions insets(toolpaths.size());
+    // Polygons show up here one by one, so there are always only a) the outer lines and b) the lines that are part of the holes.
+    // Therefore, the outer-regions' lines will always have the region-id that is larger then all of the other ones.
+
+    // First, build the bounding boxes:
+    std::map<size_t, AABB> region_ids_to_bboxes;
+    size_t max_inset_index = 0; // Also find the largest inset-index.
     for (const VariableWidthLines& path : toolpaths)
     {
+        const size_t inset_index = path.front().inset_idx;
+        max_inset_index = std::max(inset_index, max_inset_index);
+
+        if (region_ids_to_bboxes.count(inset_index) == 0)
+        {
+            region_ids_to_bboxes[inset_index] = AABB();
+        }
+        AABB& aabb = region_ids_to_bboxes[inset_index];
+
+        std::for_each(path.begin(), path.end(),
+            [&aabb](const ExtrusionLine& line) { std::for_each(line.junctions.begin(), line.junctions.end(),
+                [&aabb](const ExtrusionJunction& j) { aabb.include(j.p);
+            });
+        });
+    }
+
+    // Then, the largest of these will be the one that's needed for the outer region, the others' all belong to hole regions:
+    AABB outer_bbox;
+    size_t outer_region_id = 0; // Region-ID 0 is reserved for 'None'.
+    for (const auto& region_id_bbox_pair : region_ids_to_bboxes)
+    {
+        if (region_id_bbox_pair.second.contains(outer_bbox))
+        {
+            outer_bbox = region_id_bbox_pair.second;
+            outer_region_id = region_id_bbox_pair.first;
+        }
+    }
+
+    // Since we're (potentially) splitting off in the outer and inner regions, it may need twice as many bins as inset-indices.
+    const size_t max_bin = (max_inset_index + 1) * 2;
+    BinJunctions insets(max_bin + 1);
+    for (const VariableWidthLines& path : toolpaths)
+    {
         if (path.empty()) // Don't bother printing these.
         {
             continue;
         }
         const size_t inset_index = path.front().inset_idx;
+        const size_t region_id = path.front().region_id;
+
+        // Sort into the right bin, from the actual outer rim (0), through the middle (max_inset_index), and then back to the hole-regions (2 * max_inset_index (-1 if odd)):
+        const size_t bin_index = (region_id == outer_region_id) ? inset_index : (max_bin - inset_index);

         // Convert list of extrusion lines to vectors of extrusion junctions, and add those to the binned insets.
         for (const ExtrusionLine& line : path)
         {
-            insets[inset_index].emplace_back(line.junctions.begin(), line.junctions.end());
+            insets[bin_index].emplace_back(line.junctions.begin(), line.junctions.end());
         }
     }
     return insets;


fix a bug in qhttpclient.

fix a bug in qhttpclient.

if a socket drops by any mean before http response emits end() signal,
then the request and response instances will be deleted.

--- src/qhttpclient.cpp
+++ src/qhttpclient.cpp
@@ -123,6 +123,14 @@

 ///////////////////////////////////////////////////////////////////////////////

+// if user closes the connection, ends the response or by any other reason
+//  the socket be disconnected, then the iresponse instance may has been deleted.
+//  In these situations reading more http body or emitting end() for incoming response
+//  is not possible.
+#define CHECK_FOR_DISCONNECTED  if ( ilastResponse == nullptr ) \
+    return 0;
+
+
 int
 QHttpClientPrivate::messageBegin(http_parser*) {
     itempHeaderField.clear();
@@ -133,6 +141,7 @@

 int
 QHttpClientPrivate::status(http_parser* parser, const char* at, size_t length) {
+    CHECK_FOR_DISCONNECTED

     ilastResponse = new QHttpResponse(isocket);
     ilastResponse->d_func()->istatus  = static_cast<TStatusCode>(parser->status_code);
@@ -146,7 +155,7 @@

 int
 QHttpClientPrivate::headerField(http_parser*, const char* at, size_t length) {
-    Q_ASSERT(ilastResponse);
+    CHECK_FOR_DISCONNECTED

     // insert the header we parsed previously
     // into the header map
@@ -169,7 +178,6 @@

 int
 QHttpClientPrivate::headerValue(http_parser*, const char* at, size_t length) {
-    Q_ASSERT(ilastResponse);

     itempHeaderValue.append(at, length);
     return 0;
@@ -177,7 +185,7 @@

 int
 QHttpClientPrivate::headersComplete(http_parser*) {
-    Q_ASSERT(ilastResponse);
+    CHECK_FOR_DISCONNECTED

     // Insert last remaining header
     ilastResponse->d_func()->iheaders.insert(
@@ -195,7 +203,7 @@

 int
 QHttpClientPrivate::body(http_parser*, const char* at, size_t length) {
-    Q_ASSERT(ilastResponse);
+    CHECK_FOR_DISCONNECTED

     if ( ilastResponse->idataHandler )
         ilastResponse->idataHandler(QByteArray(at, length));
@@ -207,7 +215,7 @@

 int
 QHttpClientPrivate::messageComplete(http_parser*) {
-    Q_ASSERT(ilastResponse);
+    CHECK_FOR_DISCONNECTED

     ilastResponse->d_func()->isuccessful = true;


(BlockLevelBox::layOutText) : Fix a bug; cf. white-space-processing-049.

--- www/css/LineBox.cpp
+++ www/css/LineBox.cpp
@@ -257,6 +257,7 @@

         bool linefeed = false;
         float advanced = 0.0f;
+        bool breakLine = false;

         if (data.empty())
             inlineBox->setData(font, point, data, 0, 0);
@@ -277,7 +278,6 @@
             float advanced = 0.0f;
             float wrapWidth = 0.0f;
             context->setText(p, fitLength);
-            bool breakLine = false;
             unsigned transform = activeStyle->textTransform.getValue();

             do {
@@ -291,7 +291,7 @@
                 while (context->leftover < w && CSSWhiteSpaceValueImp::isBreakingLines(context->whiteSpace)) {
                     if (activeStyle->whiteSpace.isCollapsingSpace() && u == u' ') {
                         float lineEnd = (next - wrap == 1) ? 0 : w - glyph->advance * font->getScale(point);
-                        if (lineEnd <= context->leftover) {
+                        if (lineEnd == 0 || lineEnd <= context->leftover) {
                             w = lineEnd;
                             advanced += w;
                             context->leftover = 0.0f;
@@ -390,8 +390,11 @@
         if (data.length() <= position) {  // layout done?
             if (linefeed)
                 context->nextLine(view, this);
-            if (!wrapBox)
+            if (!wrapBox) {
+                if (breakLine)
+                    nextLine(view, context, activeStyle, firstLetterStyle, firstLineStyle, style, font, point);
                 break;
+            }
             inlineBox = wrapBox;
             wrapBox = 0;
             goto NextLine;


Fix Transforms/ScalarRepl/2007-05-29-MemcpyPreserve.ll and the second
half of PR1421, by not decimating structs with holes that are the source and
destination of a memcpy.

git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@37358 91177308-0d34-0410-b5e6-96231b3b80d8

--- lib/Transforms/Scalar/ScalarReplAggregates.cpp
+++ lib/Transforms/Scalar/ScalarReplAggregates.cpp
@@ -65,11 +65,41 @@
     }

   private:
-    int isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI);
-    int isSafeUseOfAllocation(Instruction *User, AllocationInst *AI);
-    bool isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI);
-    bool isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI);
+    /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
+    /// information about the uses.  All these fields are initialized to false
+    /// and set to true when something is learned.
+    struct AllocaInfo {
+      /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
+      bool isUnsafe : 1;
+
+      /// needsCanon - This is set to true if there is some use of the alloca
+      /// that requires canonicalization.
+      bool needsCanon : 1;
+
+      /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
+      bool isMemCpySrc : 1;
+
+      /// isMemCpyDst - This is true if this aggregate is memcpy'd info.
+      bool isMemCpyDst : 1;
+
+      AllocaInfo()
+        : isUnsafe(false), needsCanon(false),
+          isMemCpySrc(false), isMemCpyDst(false) {}
+    };
+
+    void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
+
     int isSafeAllocaToScalarRepl(AllocationInst *AI);
+
+    void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
+                               AllocaInfo &Info);
+    void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
+                         AllocaInfo &Info);
+    void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
+                                        unsigned OpNo, AllocaInfo &Info);
+    void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
+                                        AllocaInfo &Info);
+
     void DoScalarReplacement(AllocationInst *AI,
                              std::vector<AllocationInst*> &WorkList);
     void CanonicalizeAllocaUsers(AllocationInst *AI);
@@ -320,7 +350,8 @@
 /// getelementptr instruction of an array aggregate allocation.  isFirstElt
 /// indicates whether Ptr is known to the start of the aggregate.
 ///
-int SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI) {
+void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
+                            AllocaInfo &Info) {
   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
        I != E; ++I) {
     Instruction *User = cast<Instruction>(*I);
@@ -328,7 +359,7 @@
     case Instruction::Load:  break;
     case Instruction::Store:
       // Store is ok if storing INTO the pointer, not storing the pointer
-      if (User->getOperand(0) == Ptr) return 0;
+      if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
       break;
     case Instruction::GetElementPtr: {
       GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
@@ -336,7 +367,8 @@
       if (GEP->getNumOperands() > 1) {
         if (!isa<ConstantInt>(GEP->getOperand(1)) ||
             !cast<ConstantInt>(GEP->getOperand(1))->isZero())
-          return 0;  // Using pointer arithmetic to navigate the array.
+          // Using pointer arithmetic to navigate the array.
+          return MarkUnsafe(Info);

         if (AreAllZeroIndices) {
           for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
@@ -348,28 +380,34 @@
           }
         }
       }
-      if (!isSafeElementUse(GEP, AreAllZeroIndices, AI)) return 0;
+      isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
+      if (Info.isUnsafe) return;
       break;
     }
     case Instruction::BitCast:
-      if (isFirstElt &&
-          isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI))
+      if (isFirstElt) {
+        isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
+        if (Info.isUnsafe) return;
         break;
+      }
       DOUT << "  Transformation preventing inst: " << *User;
-      return 0;
+      return MarkUnsafe(Info);
     case Instruction::Call:
       if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
-        if (isFirstElt && isSafeMemIntrinsicOnAllocation(MI, AI))
+        if (isFirstElt) {
+          isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
+          if (Info.isUnsafe) return;
           break;
+        }
       }
       DOUT << "  Transformation preventing inst: " << *User;
-      return 0;
+      return MarkUnsafe(Info);
     default:
       DOUT << "  Transformation preventing inst: " << *User;
-      return 0;
-    }
-  }
-  return 3;  // All users look ok :)
+      return MarkUnsafe(Info);
+    }
+  }
+  return;  // All users look ok :)
 }

 /// AllUsersAreLoads - Return true if all users of this value are loads.
@@ -384,21 +422,25 @@
 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
 /// aggregate allocation.
 ///
-int SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI) {
+void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
+                                 AllocaInfo &Info) {
   if (BitCastInst *C = dyn_cast<BitCastInst>(User))
-    return isSafeUseOfBitCastedAllocation(C, AI) ? 3 : 0;
-  if (!isa<GetElementPtrInst>(User)) return 0;
-
-  GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
+    return isSafeUseOfBitCastedAllocation(C, AI, Info);
+
+  GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
+  if (GEPI == 0)
+    return MarkUnsafe(Info);
+
   gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);

   // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
   if (I == E ||
-      I.getOperand() != Constant::getNullValue(I.getOperand()->getType()))
-    return 0;
+      I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
+    return MarkUnsafe(Info);
+  }

   ++I;
-  if (I == E) return 0;  // ran out of GEP indices??
+  if (I == E) return MarkUnsafe(Info);  // ran out of GEP indices??

   bool IsAllZeroIndices = true;

@@ -413,7 +455,7 @@
       // something funny is going on, so we won't do the optimization.
       //
       if (Idx->getZExtValue() >= NumElements)
-        return 0;
+        return MarkUnsafe(Info);

       // We cannot scalar repl this level of the array unless any array
       // sub-indices are in-range constants.  In particular, consider:
@@ -430,9 +472,9 @@
           NumElements = cast<VectorType>(*I)->getNumElements();

         ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
-        if (!IdxVal) return 0;
+        if (!IdxVal) return MarkUnsafe(Info);
         if (IdxVal->getZExtValue() >= NumElements)
-          return 0;
+          return MarkUnsafe(Info);
         IsAllZeroIndices &= IdxVal->isZero();
       }

@@ -444,53 +486,62 @@
       // it, in which case we CAN promote it, but we have to canonicalize this
       // out if this is the only problem.
       if ((NumElements == 1 || NumElements == 2) &&
-          AllUsersAreLoads(GEPI))
-        return 1;  // Canonicalization required!
-      return 0;
+          AllUsersAreLoads(GEPI)) {
+        Info.needsCanon = true;
+        return;  // Canonicalization required!
+      }
+      return MarkUnsafe(Info);
     }
   }

   // If there are any non-simple uses of this getelementptr, make sure to reject
   // them.
-  return isSafeElementUse(GEPI, IsAllZeroIndices, AI);
+  return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
 }

 /// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
 /// intrinsic can be promoted by SROA.  At this point, we know that the operand
 /// of the memintrinsic is a pointer to the beginning of the allocation.
-bool SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI){
+void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
+                                          unsigned OpNo, AllocaInfo &Info) {
   // If not constant length, give up.
   ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
-  if (!Length) return false;
+  if (!Length) return MarkUnsafe(Info);

   // If not the whole aggregate, give up.
   const TargetData &TD = getAnalysis<TargetData>();
   if (Length->getZExtValue() != TD.getTypeSize(AI->getType()->getElementType()))
-    return false;
+    return MarkUnsafe(Info);

   // We only know about memcpy/memset/memmove.
   if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
-    return false;
-  // Otherwise, we can transform it.
-  return true;
+    return MarkUnsafe(Info);
+
+  // Otherwise, we can transform it.  Determine whether this is a memcpy/set
+  // into or out of the aggregate.
+  if (OpNo == 1)
+    Info.isMemCpyDst = true;
+  else {
+    assert(OpNo == 2);
+    Info.isMemCpySrc = true;
+  }
 }

 /// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
 /// are
-bool SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI) {
+void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
+                                          AllocaInfo &Info) {
   for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
        UI != E; ++UI) {
     if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
-      if (!isSafeUseOfBitCastedAllocation(BCU, AI))
-        return false;
+      isSafeUseOfBitCastedAllocation(BCU, AI, Info);
     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
-      if (!isSafeMemIntrinsicOnAllocation(MI, AI))
-        return false;
+      isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
     } else {
-      return false;
-    }
-  }
-  return true;
+      return MarkUnsafe(Info);
+    }
+    if (Info.isUnsafe) return;
+  }
 }

 /// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
@@ -668,6 +719,44 @@
   }
 }

+/// HasStructPadding - Return true if the specified type has any structure
+/// padding, false otherwise.
+static bool HasStructPadding(const Type *Ty, const TargetData &TD) {
+  if (const StructType *STy = dyn_cast<StructType>(Ty)) {
+    const StructLayout *SL = TD.getStructLayout(STy);
+    unsigned PrevFieldBitOffset = 0;
+    for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
+      unsigned FieldBitOffset = SL->getElementOffset(i)*8;
+
+      // Padding in sub-elements?
+      if (HasStructPadding(STy->getElementType(i), TD))
+        return true;
+
+      // Check to see if there is any padding between this element and the
+      // previous one.
+      if (i) {
+        unsigned PrevFieldEnd =
+        PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
+        if (PrevFieldEnd < FieldBitOffset)
+          return true;
+      }
+
+      PrevFieldBitOffset = FieldBitOffset;
+    }
+
+    //  Check for tail padding.
+    if (unsigned EltCount = STy->getNumElements()) {
+      unsigned PrevFieldEnd = PrevFieldBitOffset +
+                   TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
+      if (PrevFieldEnd < SL->getSizeInBytes()*8)
+        return true;
+    }
+
+  } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
+    return HasStructPadding(ATy->getElementType(), TD);
+  }
+  return false;
+}

 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
 /// an aggregate can be broken down into elements.  Return 0 if not, 3 if safe,
@@ -676,18 +765,29 @@
 int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
   // Loop over the use list of the alloca.  We can only transform it if all of
   // the users are safe to transform.
-  //
-  int isSafe = 3;
+  AllocaInfo Info;
+
   for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
        I != E; ++I) {
-    isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I), AI);
-    if (isSafe == 0) {
+    isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
+    if (Info.isUnsafe) {
       DOUT << "Cannot transform: " << *AI << "  due to user: " << **I;
       return 0;
     }
   }
-  // If we require cleanup, isSafe is now 1, otherwise it is 3.
-  return isSafe;
+
+  // Okay, we know all the users are promotable.  If the aggregate is a memcpy
+  // source and destination, we have to be careful.  In particular, the memcpy
+  // could be moving around elements that live in structure padding of the LLVM
+  // types, but may actually be used.  In these cases, we refuse to promote the
+  // struct.
+  if (Info.isMemCpySrc && Info.isMemCpyDst &&
+      HasStructPadding(AI->getType()->getElementType(),
+                       getAnalysis<TargetData>()))
+    return 0;
+
+  // If we require cleanup, return 1, otherwise return 3.
+  return Info.needsCanon ? 1 : 3;
 }

 /// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified


Parse --debug switch from command line

Parse --debug switch from command line

--- src/sqexec/main.cpp
+++ src/sqexec/main.cpp
@@ -6,40 +6,29 @@
 #include "libsqasm/assembler.hpp"
 #include "libsqrun/runner.hpp"

-static void assemble(const string &fileName, const bool debug = false)
+static void assemble(const string &fileName, const bool debug)
 {
     auto compilationData(Assembler::assemble(fileName));
-    Runner::run(compilationData->ops());
-
-    if (debug)
-    {
-        if (!compilationData->symbolTable().empty())
-        {
-            cout << "Symbol table" << endl;
-            for (auto &pair : compilationData->symbolTable())
-            {
-                cout << "  symbol: " << pair.first << " = " << pair.second << endl;
-            }
-        }
-
-        if (!compilationData->cells().empty())
-        {
-            cout << "Cells" << endl;
-            for (auto &cell : compilationData->cells())
-            {
-                cout << "  cell: " << cell->toString() << endl;
-            }
-        }
-    }
+    Runner::run(compilationData->ops(), debug);
 }

 int main(int argc, char *argv[])
 {
     try
     {
+        bool debug = false;
+
         for (auto i = 1; i < argc; ++i)
         {
-            assemble(argv[i]);
+            string arg(argv[i]);
+
+            if (i == 1 && arg.compare("--debug") == 0)
+            {
+                debug = true;
+                continue;
+            }
+
+            assemble(arg, debug);
         }
         return EXIT_SUCCESS;
     }